[英]React router v4 route onchange event
有什么方法可以在路由器使用react路由器v4進行更改時觸發事件。 我需要在每次路線更改時觸發一個功能。 我在通用react-redux應用程序的客戶端使用來自react-router-dom
BrowserRouter
和Switch
。
我通過使用其他組件包裝我的應用程序來解決這個問題 該組件在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
東西來檢測位置變化來實現相同的目標。
React:v15.x,React Router:v4.x
組件/核心/ App.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';
class LocationListener extends Component {
static contextTypes = {
router: PropTypes.object
};
componentDidMount() {
this.handleLocationChange(this.context.router.history.location);
this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
}
componentWillUnmount() {
this.unlisten();
}
handleLocationChange(location) {
// your staff here
console.log(`- - - location: '${location.pathname}'`);
}
render() {
return this.props.children;
}
}
export class App extends Component {
...
render() {
return (
<BrowserRouter>
<LocationListener>
...
</LocationListener>
</BrowserRouter>
);
}
}
index.js:
import App from 'components/core/App';
render(<App />, document.querySelector('#root'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.