Push to React Router History from Parent Component

 ̄綄美尐妖づ 提交于 2019-12-11 15:50:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!