简体   繁体   English

React 组件状态在卸载时重置

[英]React component state resets at unmounting

I need to persist step form's data as if the user clicks on other step.我需要保留步骤表单的数据,就像用户单击其他步骤一样。 So during unmounting of step form component, I need to update the state to REDUX store因此,在卸载步骤表单组件期间,我需要将状态更新为 REDUX 存储

Issue问题

The state seems to be resetting to default as soon as I am accessing it while unmounting;一旦我在卸载时访问它,状态似乎就会重置为默认值;

// local state 
  const [state, setState] = React.useState({
    named: [{ id: uuid(), value: '', name: '', type: ' ' }], // 👈 initial state
  });

  React.useEffect(() => {
    // update redux state before unmounting
    return () => {
      // 👇 sets itself to initial state ignoring what user has typed
      console.log(state); // prints [{ id: uuid(), value: '', name: '', type: ' ' }]       
      updateStepThreeReduxState(state); // redux action
    };
  }, []);

Is there any way we can get an access to the state just before unmouting ??有什么办法可以在卸载之前访问状态?

State and updateStepThreeReduxState are dependencies of your effect: State 和 updateStepThreeReduxState 是效果的依赖项:

//custom hook defined outside the component
function useIsMounted() {
  const isMounted = useRef(false)
  useEffect(() => {
    isMounted.current = true
    return () => {
      isMounted.current = false
    }
  }, [])
  return () => isMounted.current
}

// local state
const [state, setState] = React.useState({
  named: [{ id: uuid(), value: '', name: '', type: ' ' }], // 👈 initial state
});
const mounted = useIsMounted()
React.useEffect(() => {
  // update redux state before unmounting
  return () => {
    if(!mounted()){
      console.log(state); // prints [{ id: uuid(), value: '', name: '', type: ' ' }]
      updateStepThreeReduxState(state); // redux action
    }
  };
}, [state, updateStepThreeReduxState,mounted]);//<- added dependencies

Because you didn't add it to dependencies you have a state value that is a stale closure .因为您没有将它添加到依赖项,所以您的状态值是一个陈旧的闭包 Missing dependencies should cause a warning with the linter , create react app should have set all of this up for you so either use create-react-app or stop ignoring the warnings it produces.缺少依赖项应该会导致linter警告,create react app 应该已经为你设置了所有这些,所以要么使用 create-react-app 要么停止忽略它产生的警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM