React Router DOM侦听路由更改

时间:2020-11-12 17:47:50

标签: javascript reactjs react-router-dom

我的react应用程序位于java struts项目中,该项目包含一个标头。该标头中的某个元素会根据所击中的某些路线而变化。

为此,当路线在定义“我的路线”的位置发生更改时,监听起来会容易得多。而不是在每条路线上都这样做。

这是我的

App.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>
  );
}

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

更新了您的代码和框:

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