【发布时间】:2020-11-09 13:54:45
【问题描述】:
如果状态变量 can_update 为真,我在 useEffect 中设置了一个间隔,以每 33 秒更新一次数据。 can_pdate 的初始值 = true。问题是,即使我将 can_update 更改为 false(使用 disable_update 函数),在 update_groups 函数中它仍然为 true。
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。没有变化。
我在一个类组件中有一些类似的代码,似乎没有任何这样的问题。
【问题讨论】:
-
看起来你的
useEffect钩子应该包含update_groups函数作为依赖项(而不是project_data.id)。您还需要将update_groups包装在带有相关依赖项的useCallback钩子中(can_update和project_data.id)。 -
另外,就其价值而言,您似乎不需要为
intervalRef使用参考。只需一个常规变量就足够了。
标签: javascript reactjs setinterval react-functional-component