[英]How to run React useEffect only once and property update state with setState
The following functional React component runs the useEffect hook twice, even though an empty array [] is passed as a second argument and the component is added to the page only once:下面的函数式 React 组件运行 useEffect 钩子两次,即使一个空数组 [] 作为第二个参数传递并且组件只添加到页面一次:
const Tips = () => {
const [idx, setIdx] = useState(0)
useEffect(() => {
const interval = setInterval(() => {
setIdx(idx + 1)
}, 1000)
}, []) // empty array: run effect only once
return <>{idx}</>
}
How to make sure the interval is started only once inside the useEffect function callback?如何确保间隔在 useEffect 函数回调中仅启动一次?
Also, the state idx is updated only once, the component outputs 0 and later on 1. How to change the component so that the idx counter keeps increasing?此外,状态 idx 仅更新一次,组件输出 0 和稍后输出 1。如何更改组件以使 idx 计数器不断增加?
This code will do what you need:此代码将执行您需要的操作:
const Tips = () => {
const [idx, setIdx] = React.useState(0);
React.useEffect(() => {
console.log("start use effect");
const interval = setInterval(() => {
setIdx(idx=>idx + 1);
}, 1000);
return ()=>clearInterval(interval)
}, []); // empty array: run effect only once
return <>{idx}</>;
};
the trick is here setIdx(idx=>idx + 1)
.诀窍在这里
setIdx(idx=>idx + 1)
。 Instead of setIdx(idx + 1)
.而不是
setIdx(idx + 1)
。 Because useEffect runs once, interval handler creates a closure over your initial idx value which is 0 and on every setIdx it just sets it to 0+1 and then component re-rendered with 1.因为 useEffect 运行一次,所以间隔处理程序会在初始 idx 值为 0 的基础上创建一个闭包,并且在每个 setIdx 上它只是将其设置为 0+1,然后将组件重新渲染为 1。
useEffect is only called once when I try to implement it. useEffect 仅在我尝试实现它时调用一次。 The interval function is however stuck in a loop.
然而,区间函数陷入了循环。 I think it is unclear what you want to achieve with this?
我认为目前还不清楚你想用这个实现什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.