[英]Why does setInterval works in useEffect but not when inside functional component context (see inside if condition)?
[英]Condition inside setInterval in functional component
如果 state 变量 can_update 为真,我在 useEffect 中设置了一个间隔以每 33 秒更新一次数据。 can_pdate 的初始值 = true。 问题是,即使我将 can_update 更改为 false(使用 disable_update 函数),在 update_groups function 中它仍然是正确的。
const [can_update, set_can_update] = useState(true);
const [groups, set_groups] = useState([]);
const intervalRef = useRef();
useEffect(() => {
update_groups();
const update_interval = setInterval(() => {
update_groups();
}, 33000);
intervalRef.current = update_interval;
return () => {
clearInterval(intervalRef.current);
};
}, [project_data.id]);
const update_groups = () => {
if (can_update) {
UI.get(`/project/${project_data.id}/controllers/`).then(
(data) => {
set_groups(data.groups);
},
(error) => {
console.log("Не удалось загрузить список групп");
},
);
}
};
const enable_update = () => {
set_can_update(true);
};
const disable_update = () => {
set_can_update(false);
};
我已经尝试将条件移动到
setInterval: `const update_interval = setInterval(() => {
if (can_update){ update_groups()};
}
并将setInterval
替换为递归setTimeout
。 没有变化。
我在 class 组件中有一些类似的代码,并且似乎没有这样的问题。
您需要将can_update
添加到useEffect
,否则
来自组件 scope 的所有值(例如道具和状态)随时间变化并由效果使用。 https://reactjs.org/docs/hooks-effect.html
在您的情况下, useEffect
被调用一次,在其中每 33 秒调用一次 function update_groups
,其范围值为can_update = true
。
React.useEffect(() => {
if (can_update) {
update_groups();
const update_interval = setInterval(() => {
update_groups();
}, 33000);
intervalRef.current = update_interval;
return () => {
clearInterval(intervalRef.current);
};
}
}, [project_data.id, can_update]);
const update_groups = () => {
UI.get(`/project/${project_data.id}/controllers/`).then(
data => {
set_groups(data.groups);
},
error => {
console.log('Не удалось загрузить список групп');
},
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.