我可以看到我的状态值在useEffect中被更新,但是,在每5秒触发一次的函数中,值仍然是相同的。有办法解决这个问题吗?
const [check, setCheck] = useState(true);
// Button to toggle Check
const buttonToToggleCheckValue = () => {
console.log("Toggle check");
setCheck(!check);
};
// Call this function every 5 seconds
const triggeredEveryFiveSeconds = () => {
console.log("Check value: " + check);
};
useEffect(() => {
console.log("useEffect Check value: " + check);
}, [check]);
---output---
Check value: true
Check value: true
Check value: true
Toggle check
useEffect Check value: false
Check value: true <--- Value should be false
Check value: true
Check value: true
问题是,每当状态改变时,组件就会重新呈现并将状态初始化为true。您可以使用useRef,如下面的代码片段所示。
const check = useRef(true);
// Button to toggle Check
const buttonToToggleCheckValue = () => {
console.log('Toggle check');
check.current = !check.current
};
// Call this function every 5 seconds
const triggeredEveryFiveSeconds = () => {
console.log('Check value: ' + check.current);
};
useEffect(() => {
console.log('useEffect Check value: ' + check.current);
}, [check]);
useEffect(() => {
setInterval(() => {
triggeredEveryFiveSeconds();
}, 5 * 1000);
}, []);
ref将在多次渲染中保持该值。