javascript - 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来测试这个问题。
解决方案
请记住,react-router-dom
将导航对象向下传递到 React 树。
您正在尝试访问 App 组件中的历史记录和位置,但是您的 App 组件“上方”没有任何东西可以为其提供历史记录或位置。
如果您将useLocation
anduseHistory
放在 PageOne/PageTwo/PageThree 组件中,它会按预期工作。
更新了您的代码框:
https://codesandbox.io/s/loving-lamarr-bzspg?fontsize=14&hidenavigation=1&theme=dark
推荐阅读
- c# - Xamarin 表单 - 根据单击的按钮更改页面内容
- reactjs - 如何在 React DraftJS 编辑器中存储 textAlignment 值?
- angular - 在 Angular 10 中使用羽毛笔编辑器自定义字体大小
- python - Django 动态设置:从管理页面访问 DEBUG
- c++ - free():使用 scanf 时指针无效
- javascript - 我可以让 React 在开发中以不同的方式编译对象扩展运算符吗?
- python - 变分自编码器的潜在维度分析:为什么使用 z_mean 而不是 z?
- python-3.x - 如何将colab中的音频文件转换为文本?
- php - 检查是否可以使用 laravel 识别路线
- gcc - gcc 10.3.1.1.fc32 构建失败并显示“gcc:致命错误:'-fuse-linker-plugin',但未找到 liblto_plugin.so”