我正在创建间隔计数器,下面的代码工作正常。但我对这段代码有几个我不理解的问题。
import React, { useState, useEffect } from 'react';
import {View, Text} from 'react-native'
const Interval = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
console.log(`seconds: ${seconds}`)
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<View>
<Text>
{seconds} seconds have elapsed since mounting.
</Text>
</View>
);
};
export default IntervalExample;
- 如果我输入
setSeconds(seconds => seconds + 1);
,为什么这不起作用?相反setSeconds(seconds + 1);
更简单吗? - 为什么
console.log(`seconds: ${seconds}`)
始终记录为0
?
最佳答案
要运行useEffect
,您需要传递变量作为第二个参数(在您的例子中,它是秒
)。当此变量更改时,useEffect
将再次运行。
来自文档:
If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often. Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.
也就是说,您需要将第二个变量传递给 useEfect:
useEffect(() => {...}, [seconds])
在这种情况下,您可以使用 setSeconds(seconds + 1);
而不是传递函数。
完整代码:
useEffect(() => {
const interval = setInterval(() => {
console.log(`seconds: ${seconds}`)
setSeconds(seconds + 1)
}, 1000)
return () => clearInterval(interval)
}, [seconds])
关于reactjs - React 原生 setInterval useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67803897/