history.listen()尝试检测路线变化时,可以使用功能。考虑到您正在使用
react-router v4,请用
withRouterHOC 包装您的组件以访问
history道具。
history.listen()返回一个
unlisten函数。您将使用它来
unregister收听。
您可以像这样配置路线
index.js
ReactDOM.render( <BrowserRouter> <AppContainer> <Route exact path="/" Component={...} /> <Route exact path="/Home" Component={...} /> </AppContainer> </BrowserRouter>, document.getElementById('root') );然后在 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);从历史文档:
您可以使用收听当前位置的更改
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}`)
})location对象实现window.location接口的子集,包括:
**location.pathname** - The path of the URL**location.search** - The URL query string**location.hash** - The URL hash fragment位置也可能具有以下属性:
location.state- 此位置的某些其他状态,不在URL中(在
createBrowserHistory和中
受支持createMemoryHistory)location.key-代表此位置的唯一字符串(createBrowserHistory和中支持createMemoryHistory)该操作是
PUSH, REPLACe, or POP取决于用户如何访问当前URL的操作之一。
当您使用react-router v3时,您可以使用如上所述的
history.listen()from
history包,也可以使用
browserHistory.listen()
您可以配置和使用您的路线,例如
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> ) }}


