繁体   English   中英

React 组件状态在卸载时重置

[英]React component state resets at unmounting

我需要保留步骤表单的数据,就像用户单击其他步骤一样。 因此,在卸载步骤表单组件期间,我需要将状态更新为 REDUX 存储

问题

一旦我在卸载时访问它,状态似乎就会重置为默认值;

// 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
    };
  }, []);

有什么办法可以在卸载之前访问状态?

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

因为您没有将它添加到依赖项,所以您的状态值是一个陈旧的闭包 缺少依赖项应该会导致linter警告,create react app 应该已经为你设置了所有这些,所以要么使用 create-react-app 要么停止忽略它产生的警告。

暂无
暂无

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

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