问题
I want to control the router component <HashRouter></HashRouter> from my application's root level <App> </App>component (which contains the router as a child).
class App extends Component {
componentDidMount(){
// potentially push to history here
}
render () {
<HashRouter></HashRouter>
}
}
Is this possible? (Using react-router-dom at 4.2.2)
回答1:
Non-route component can use withRouter (it's actually a wrapper for <Route children>) in order to get access to router-specific props, particularly history.
withRouter component should reside inside router so it cannot be applied to App. potentially push to history here task should be delegated to <Router> child component enhanced with withRouter:
@withRouter
class Child extends Component {
componentDidMount() {
this.props.history.push(...);
}
render () {
return null;
}
}
来源:https://stackoverflow.com/questions/53148699/push-to-react-router-history-from-parent-component