首页 > 解决方案 > React Router DOM 监听路由变化

问题描述

我的反应应用程序位于一个 java struts 项目中,其中包括一个标头。该标头中的某个元素会根据被命中的某些路由而变化。

为此,在定义我的路线的位置更改路线时收听会更简单。而不是在每条路线上都这样做。

这是我的

应用程序.js

import {
  BrowserRouter as Router,
  Route,
  useHistory,
  useLocation,
  Link
} from "react-router-dom";

const Nav = () => {
  return (
    <div>
      <Link to="/">Page 1 </Link>
      <Link to="/2">Page 2 </Link>
      <Link to="/3">Page 3 </Link>
    </div>
  );
};

export default function App() {
  const h = useHistory();
  const l = useLocation();

  const { listen } = useHistory();

  useEffect(() => {
    console.log("location change");
  }, [l]);

  useEffect(() => {
    console.log("history change");
  }, [h]);

  h.listen(() => {
    console.log("history listen");
  });

  listen((location) => {
    console.log("listen change");
  });

  return (
    <Router>
      <Route path={"/"} component={Nav} />
      <Route path={"/"} component={PageOne} exact />
      <Route path={"/2"} component={PageTwo} exact />
      <Route path={"/3"} component={PageThree} exact />
    </Router>
  );
}

单击导航组件中的链接时,没有任何控制台日志被命中。有没有解决的办法?

我有一个CodeSandbox来测试这个问题。

标签: javascriptreactjsreact-router-dom

解决方案


请记住,react-router-dom将导航对象向下传递到 React 树。

您正在尝试访问 App 组件中的历史记录和位置,但是您的 App 组件“上方”没有任何东西可以为其提供历史记录或位置。

如果您将useLocationanduseHistory放在 PageOne/PageTwo/PageThree 组件中,它会按预期工作。

更新了您的代码框:

https://codesandbox.io/s/loving-lamarr-bzspg?fontsize=14&hidenavigation=1&theme=dark


推荐阅读