React hooks - 当我们刷新页面时从 react-router 位置状态中删除

hei*_*584 8 reactjs react-router react-hooks

当我进入应用程序的一页时,我使用 react-router 通过位置状态传递数据。然后我通过location.state.myDataObject. 当我刷新页面时它仍然存在,而我希望它是空的。这是我尝试使用的内容:

  const resetLocation = () => {
    history.replace({
      ...location,
      state: undefined,
    });
  };

  useEffect(() => {
    window.addEventListener('onbeforeunload', resetLocation);
  }, []);
Run Code Online (Sandbox Code Playgroud)

或者将其添加到unmount操作中,useEffect但我想刷新页面时不会调用它:

  useEffect(() => {
    return function cleanLocationState() {
      history.replace({
        ...this.props.location,
        state: undefined,
      });
    };
  }, []);
Run Code Online (Sandbox Code Playgroud)

And*_*rea 0

你试试相反的方法怎么样?将值存储在组件上,并将其从该位置删除。我不确定这是最漂亮的解决方案,但我想这是最简单的

const [state,setState]=useState();

useEffect(()=>{
  setState(location.state);
  location.state=undefined;
}, [location])
Run Code Online (Sandbox Code Playgroud)