gpt4 book ai didi

reactjs - 如何使用react-router v4检测路由变化?

转载 作者:行者123 更新时间:2023-12-03 13:19:32 25 4
gpt4 key购买 nike

我需要检测是否发生了路由更改,以便我可以将变量更改为 true。

我已经研究过这些问题:
1.https://github.com/ReactTraining/react-router/issues/3554
2.How to listen to route changes in react router v4?
3.Detect Route Change with react-router

他们都没有为我工作过。当路由发生变化时,是否有明确的方法来调用函数。

最佳答案

一种方法是使用 withRouter 高阶组件。

<强> Live demo (单击超链接可更改路线并在显示的控制台中查看结果)

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

import {withRouter} from 'react-router-dom';

class App extends Component {
componentDidUpdate(prevProps) {
if (this.props.location.pathname !== prevProps.location.pathname) {
console.log('Route change!');
}
}
render() {
return (
<div className="App">
...routes
</div>
);
}
}

export default withRouter(props => <App {...props}/>);
<小时/>

另一个使用 url 参数的示例:

如果您要将配置文件路由从 /profile/20 更改为 /profile/32

您的路线被定义为 /profile/:userId

componentDidUpdate(prevProps) {
if (this.props.match.params.userId !== prevProps.match.params.userId) {
console.log('Route change!');
}
}

关于reactjs - 如何使用react-router v4检测路由变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com