Javascript 功能组件中setInterval内的条件
如果状态变量can\u update为true,我在useffect中设置了一个间隔,每33秒更新一次数据。 can_pdate的初始值=真。问题是,即使我将can_update更改为false(使用disable_update函数),在update_groups函数中它仍然是trueJavascript 功能组件中setInterval内的条件,javascript,reactjs,setinterval,react-functional-component,Javascript,Reactjs,Setinterval,React Functional Component,如果状态变量can\u update为true,我在useffect中设置了一个间隔,每33秒更新一次数据。 can_pdate的初始值=真。问题是,即使我将can_update更改为false(使用disable_update函数),在update_groups函数中它仍然是true const [can_update, set_can_update] = useState(true); const [groups, set_groups] = useState([]); con
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()};
}
并将递归的setTimeout
替换为setInterval
。没有变化
我在一个类组件中有一些类似的代码,并且似乎没有任何类似的问题。您需要将
can\u update
添加到useffect
deps,否则
所有价值观
从组件范围(如道具和状态)更改
效果所使用的时间和时间。
在您的情况下,useffect
被调用一次,在它内部每33秒调用一个函数update\u groups
,其作用域值为can\u 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('Не удалось загрузить список групп');
},
);
};
看起来您的
useffect
挂钩应该包含update\u groups
函数作为依赖项(而不是project\u data.id
)。您还需要将update\u组
包装在useCallback
钩子中,并附带相关的依赖项(can\u update
和project\u data.id
)。只要一个正则变量就足够了。