台州外贸网站,layui加入wordpress,顺企网查企业电话,四川省铁路建设有限公司网站一、使用react-router库#xff08;以react-router-dom为例#xff09;
1. 历史#xff08;history#xff09;对象监听
1.1 原理
react-router内部使用history对象来管理路由历史记录。可以通过访问history对象来监听路由变化。在基于类的组件中#xff0c;可以通过组…一、使用react-router库以react-router-dom为例
1. 历史history对象监听
1.1 原理
react-router内部使用history对象来管理路由历史记录。可以通过访问history对象来监听路由变化。在基于类的组件中可以通过组件的props获取history对象在函数式组件中可以使用useHistory钩子函数获取。
1.2 示例基于类的组件
import React from react;import { withRouter } from react-router-dom;class MyComponent extends React.Component {componentDidMount() {this.props.history.listen((location, action) {console.log(路由发生变化新位置:, location);console.log(路由变化的动作:, action);});}render() {return div这是一个组件/div;}}export default withRouter(MyComponent);
在这里componentDidMount生命周期方法中通过this.props.history.listen来添加一个路由变化的监听器。每当路由发生变化时就会打印出新的位置location和路由变化的动作action如PUSH、REPLACE等。
1.3 示例函数式组件
import React from react;import { useHistory } from react-router-dom;function MyComponent() {const history useHistory();React.useEffect(() {const unlisten history.listen((location, action) {console.log(路由发生变化新位置:, location);console.log(路由变化的动作:, action);});return () {unlisten();};}, [history]);return div这是一个函数式组件/div;}export default MyComponent;
在函数式组件中使用useHistory钩子获取history对象然后在useEffect钩子中添加监听器。同时返回一个清理函数用于在组件卸载时移除监听器。
2. useLocation钩子监听推荐用于函数式组件
2.1 原理
useLocation是react-router-dom提供的一个钩子函数它返回当前的location对象。通过比较前后location对象的变化可以检测到路由是否发生了变化。
2.2 示例
import React from react;import { useLocation } from react-router-dom;function MyComponent() {const location useLocation();React.useEffect(() {console.log(当前路由位置:, location);}, [location]);return div这是一个函数式组件/div;}export default MyComponent;
在这里useEffect钩子依赖location对象。每当location发生变化即路由变化时useEffect中的回调函数就会被执行打印出当前的路由位置。
3. 自定义事件监听不依赖react-router内部机制
3.1 原理
在顶层组件如App组件中通过window对象的addEventListener方法监听hashchange对于哈希路由或popstate对于 HTML5 历史记录路由事件来检测路由变化。这种方法比较底层需要自己处理更多的细节比如区分不同类型的路由和处理事件冒泡等问题。
3.2 示例以哈希路由为例
import React from react;function App() {React.useEffect(() {const handleHashChange () {console.log(哈希路由发生变化当前哈希:, window.location.hash);};window.addEventListener(hashchange, handleHashChange);return () {window.removeEventListener(hashchange, handleHashChange);};}, []);return div{/* 路由相关组件和内容 */}/div;}export default App;
在App组件的useEffect钩子中添加了一个hashchange事件监听器。当哈希路由发生变化时就会打印出当前的哈希值。注意在返回的清理函数中要移除添加的监听器以避免内存泄漏。