react - router withRouter does not inject router

前端 未结 1 1328
别跟我提以往
别跟我提以往 2021-01-20 18:53

I want to use withRouter on my top-level React component called \'App\'.

Documentation is here: https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2

相关标签:
1条回答
  • 2021-01-20 19:30

    That is happening because you are injecting the router after you render the react app.

    const App = React.createClass({
      render() {
          return (
              <div>
                  <AppBar
                    title="Democratizer"
                    onTitleTouchTap={()=>this.props.router.push('/')}
                  >
                  </AppBar>
                  <br/>
    
                {this.props.children}
              </div>
          );
      }
    });
    
    App = withRouter(App);
    
    
    render((
      <MuiThemeProvider muiTheme={getMuiTheme()}>
        <Router history={hashHistory}>
          <Route path="/" component={App}>
              <Route path="voteview/:baselineId" component={VoteView}/>
              <IndexRoute component={OverView}/>
          </Route>
        </Router>
      </MuiThemeProvider>
      ), document.getElementById('app'));
    

    A better solution would be creating a file for App like you have done with the other components.

    const App = React.createClass({
      render() {
          return (
              <div>
                  <AppBar
                    title="Democratizer"
                    onTitleTouchTap={()=>this.props.router.push('/')}
                  >
                  </AppBar>
                  <br/>
    
                {this.props.children}
              </div>
          );
      }
    });
    
    module.exports = withRouter(App);
    

    and import it in your index.js.

    0 讨论(0)
提交回复
热议问题