首页 > 解决方案 > React hooks - 当我们刷新页面时从 react-router 位置状态中删除

问题描述

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

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

  useEffect(() => {
    window.addEventListener('onbeforeunload', resetLocation);
  }, []);

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

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

标签: reactjsreact-routerreact-hooks

解决方案


我认为这是反应路由器的期望行为。如果你想重置状态,那么你需要做类似的事情

import React, { useEffect, useCallback } from "react";
import { useLocation, useHistory } from "react-router-dom";

function Home() {
  const location = useLocation();
  const history = useHistory();
  const replaceHistory = useCallback(() => {
    history.replace({ ...location, state: undefined });
  }, [history]);

  useEffect(() => {
    window.addEventListener("beforeunload", () => replaceHistory);
    return () => {
      window.removeEventListener("beforeunload", replaceHistory);
    };
  }, []);

  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

export default Home;

工作示例


推荐阅读