当组件重新租赁时,请防止提取
我有一个简单的网站,我可以获取数据并获得一系列OBJ,并在测验页面上显示它,但我也实现了倒计时。问题是,每当计时器再次呈现时,我每秒都会得到不同的数组。如何防止最初的obj更改?
我从usecontext获取了阵列
const Quiz = () =>{
useEffect(() => {
countDown();
}, [num]);
let timer;
const countDown = () => {
if (num > 0) {
timer = setTimeout(() => {
setNum(num - 1);
}, 1000);
}
if(num === 0){
nextQuestion()
}
return num;
};
return(...)
}
I have this simple website where I fetch data and get an array of Obj, and display it on the Quiz page, but I also implement a countdown. The problem is that every time the timer renders the fetch run again and I get a different array every sec. How Do I prevent the initial obj I fetch from changing?
Im getting the fetch array from useContext
const Quiz = () =>{
useEffect(() => {
countDown();
}, [num]);
let timer;
const countDown = () => {
if (num > 0) {
timer = setTimeout(() => {
setNum(num - 1);
}, 1000);
}
if(num === 0){
nextQuestion()
}
return num;
};
return(...)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要从使用效率的依赖项数组中删除NUM。
当您添加依赖项以使用效果时,它将每次更改时都会呈现,并且您只希望倒计时一次运行。
通常,您还应该将倒计时组件与Usecallback包裹,并将倒计时作为对使用效应的依赖性
,现在这应该解决您的问题 -
You need to remove the num from the dependency array of useEffect.
When you add a dependency to useEffect it will re render every time it changes, and you only want countDown to run once.
Usually you should also wrap the countDown component with useCallback and put the countDown as a dependency on the useEffect
anyway, for now this should solve your issue -
这会回答您的问题吗?
does this answer your question ?