当使用 react router v4.1 更改路由时,是否有任何方法可以触发事件?我需要在每次路线更改时触发一个功能。我在通用 react-redux 应用程序的客户端使用来自 BrowserRouter
的 Switch
和 react-router-dom
。
最佳答案
我通过用附加组件包装我的应用程序解决了这个问题。该组件用于 Route
中,因此它也可以访问 history
属性。
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
App
组件订阅历史更改,因此每当路由更改时我都可以做一些事情:export class App extends React.Component {
componentWillMount() {
const { history } = this.props;
this.unsubscribeFromHistory = history.listen(this.handleLocationChange);
this.handleLocationChange(history.location);
}
componentWillUnmount() {
if (this.unsubscribeFromHistory) this.unsubscribeFromHistory();
}
handleLocationChange = (location) => {
// Do something with the location
}
render() {
// Render the rest of the application with its routes
}
}
不确定这是否是在 V4 中执行此操作的正确方法,但我没有在路由器本身上找到任何其他扩展点,因此这似乎有效。希望有帮助。
编辑:也许您也可以通过将
<Route />
包装在您自己的组件中并使用 componentWillUpdate
之类的东西来检测位置更改来实现相同的目标。