状态更改不会在另一个卸载使用中受到影响

时间:2019-04-11 07:50:39

标签: javascript reactjs redux react-hooks

对Hooks做出反应的新手。

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

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

因为钩子中没有回调函数,所以我等到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状态。

我在上面的卸载钩子上打印了clearSelected。是的。

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

2 个答案:

答案 0 :(得分:0)

您基本上在第二个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);
        }
    })
}, []);

答案 1 :(得分:0)

clearSelected为假的原因是因为闭包。

您的功能

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

在安装时获得clearSelected状态。您可以阅读有关Closures here的更多信息。

您将需要使用useRef,它的值为current才能使代码正常工作。

此外,here is a guide on useEffect,作者Dan Abromov。它将帮助您了解useEffect

相关问题