gpt4 book ai didi

javascript - 在 React 钩子(Hook)中的另一个卸载 useEffect 中,状态的改变不会受到影响

转载 作者:行者123 更新时间:2023-11-29 15:58:49 25 4
gpt4 key购买 nike

React Hooks 的新手。

// create as state using useState
const [clearSelected,setClearSelected] = useState(true);

//clearSelected is changed to false
setClearSelected(false);

由于钩子(Hook)中没有回调函数,所以我等到 clearSelected 变为 false 然后我移动到另一个页面

 useEffect(()=>{
//clear selected is set to false and then redirection to another page is done

if(clearSelected === false){

history.push('/nextPage');
}
},[clearSelected]);
//clears the redux state on unmount
useEffect(()=>{
return (()=>{
//should not go inside when clearSelected is false
if(clearSelected){
//clear the redux state
actions.items([], false);
}
})
},[]);

即使在 clearSelected 变为 false 后完成重定向,redux 状态也会被清除。

我在上面的卸载 Hook 中打印了 clearSelected。这是真的。

我可以知道为什么它不起作用吗?谢谢。

最佳答案

您基本上在第二个 useEffect 中创建了一个闭包,它有效地锁定了状态的初始值 (true):

useEffect(()=>{ 
return (()=>{ // closure that holds initial value of the `clearSelected`
// ...
})
},[]);

如果您想在闭包中保留对当前状态的访问权,请考虑使用 useRef 存储对它的引用。 .

所以,像这样:

const [clearSelected, setClearSelected] = useState(true);
const clearSelectedRef = useRef(clearSelected);

useEffect(() => {
clearSelectedRef.current = clearSelected;
if (clearSelected === false) {
history.push('/nextPage');
}
}, [clearSelected]);

useEffect(() => {
return (() => {
//should not go inside when clearSelected is false
if (clearSelectedRef.current) {
//clear the redux state
actions.items([], false);
}
})
}, []);

关于javascript - 在 React 钩子(Hook)中的另一个卸载 useEffect 中,状态的改变不会受到影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55627319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com