Anda dapat menggunakan history.listen()fungsi saat mencoba mendeteksi perubahan rute. Mengingat Anda sedang menggunakan react-router v4, bungkus komponen Anda dengan withRouterHOC untuk mendapatkan akses ke historyprop.
history.listen()mengembalikan suatu unlistenfungsi. Anda akan menggunakan ini untuk unregistermendengarkan.
Anda dapat mengonfigurasi rute Anda seperti
index.js
ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Route exact path="/" Component={...} />
<Route exact path="/Home" Component={...} />
</AppContainer>
</BrowserRouter>,
document.getElementById('root')
);
dan kemudian di AppContainer.js
class App extends Component {
componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default withRouter(App);
Dari dokumen sejarah :
Anda dapat mendengarkan perubahan lokasi saat ini menggunakan
history.listen:
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
Objek lokasi mengimplementasikan subset dari antarmuka window.location, termasuk:
**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment
Lokasi mungkin juga memiliki properti berikut:
location.state - Beberapa status ekstra untuk lokasi ini yang tidak berada di URL (didukung di createBrowserHistorydan
createMemoryHistory)
location.key- String unik yang mewakili lokasi ini (didukung di createBrowserHistorydan createMemoryHistory)
Tindakannya PUSH, REPLACE, or POPbergantung pada bagaimana pengguna sampai ke URL saat ini.
Ketika Anda menggunakan react-router v3 Anda dapat menggunakan history.listen()dari historypaket seperti yang disebutkan di atas atau Anda juga dapat menggunakannyabrowserHistory.listen()
Anda dapat mengonfigurasi dan menggunakan rute Anda seperti
import {browserHistory} from 'react-router';
class App extends React.Component {
componentDidMount() {
this.unlisten = browserHistory.listen( location => {
console.log('route changes');
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<Route path="/" onChange={yourHandler} component={AppContainer}>
<IndexRoute component={StaticContainer} />
<Route path="/a" component={ContainerA} />
<Route path="/b" component={ContainerB} />
</Route>
)
}
}