我知道这个问题相当普遍,我已经按照那里列出的解决方案,但没有成功,这就是为什么我提出了一个新问题。
我试图在React Native上创建一个时间/时钟(如果有人有一个库可以做到这一点,那也会很感激),目前是这样创建的。
const [time, setTime] = useState(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
function TimeView() {
setTime(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
const timeVar = setInterval(TimeView, 60000);
我试着用const、var、let来表示timeVar,但没有成功。
当用户移动到下一个屏幕时,让定时器关闭,就像这样。
<Button
onPress={{
// navigation code here
clearInterval(timeVar);
</Button>
我不知道我在这里做错了什么,希望得到任何帮助。谢谢!
Edit:根据Uğur Eren的建议,我定义了这个函数,但是定时器并没有通过这个方法工作。
function Interval(fn, time) {
const timer = useRef();
this.start = function () {
if (!this.isRunning()) {
timer.current = setInterval(fn, time);
this.stop = function () {
clearInterval(timer);
timer.current = false;
this.isRunning = function () {
return timer !== false;