未在浏览器后退按钮上调用useEffect清理

时间:2019-11-22 02:14:51

标签: reactjs react-router

我正在使用react-router v5.1,并试图在导航到其他页面时清除会话变量。如果单击页面上的链接,则会触发清除回调,但是,如果我使用浏览器后退按钮,则路由会更改,但不会触发清除回调。

我真的不想挂在react-router的location / routes / etc上,因为这是完成我想做的事情的一种非常简单的方法,而且我显然不了解useEffect发生了什么,所以它更好地解决这个问题。

谢谢!

const LinkProvider: React.FC = () => {
  const location = useLocation
  useEffect(() => {
    return (): void => {
      console.log('unmount');
      sessionStorage.removeItem("key");
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  return (<div></div>)
}

我也尝试过

const LinkProvider: React.FC = () => {
  useEffect(() => {
    return (): void => {
      console.log('unmount');
      sessionStorage.removeItem("key");
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (<div></div>)
}

1 个答案:

答案 0 :(得分:1)

这是我的代码。我想知道您的代码中出了什么问题。 您使用的是“ react-router”而不是“ react-router-dom”吗?

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import LandingPage from "./components/LandingPage";
import ProfilePage from "./components/ProfilePage";
import "./styles.css";

function App() {
  return (
    <Router>
      <Switch>
        <Route path={"/"} exact>
          <LandingPage />
        </Route>
        <Route path="/profile">
          <ProfilePage />
        </Route>
      </Switch>
    </Router>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

components / ProfilePage.js

import React from "react";
import { Link } from "react-router-dom";

const ProfilePage = () => {
  React.useEffect(() => {
    return () => {
      console.log("Profile page unmount");
      sessionStorage.removeItem("key");
    };
  }, []);

  return (
    <div>
      <h1>Hello, This is the home page</h1>
      <Link to="/">Go to Landing</Link>
    </div>
  );
};

export default ProfilePage;

components / LandingPage.js

import React from "react";
import { Link } from "react-router-dom";

const LandingPage = () => {
  React.useEffect(() => {
    return () => {
      console.log("Landing page unmount");
      sessionStorage.removeItem("key");
    };
  });

  return (
    <div>
      <h1>Hello, This is the home page</h1>
      <Link to="/profile">Go to Profile</Link>
    </div>
  );
};

export default LandingPage;

这是codeandbox的链接。工作正常。 https://codesandbox.io/s/nifty-shaw-7bofu