简体   繁体   中英

React router dom not rendering child component but url changed

I have child routes and when I'm trying to change the routes in AppMain.js its changing the url but the component is not getting rendered, instead the existing component is getting re-rendered. But if I am doing the same history.push inside Dashboard or BatteryTable the route is working fine.

App.js

<Router>
  <Route exact path="/" component={withRouter(Auth)} />
  <Route path="/main" component={withRouter(AppMain)} />
</Router>

AppMain.js

constructor(props) {
    super(props)
    this.props.history.push('/main/dashboard')  
}

render() {
    return(
        <Routes match={match} />
    )
}

Routes.js

<Router>
    <Switch>
        <Route path={`${this.props.match.path}/dashboard`} component={withRouter(Dashboard)} />
        <Route path={`${this.props.match.path}/batterytable`} component={withRouter(BatteryTable)} />
    </Switch>
</Router>

Its because you are using Router component twice, remove it from Routes.js file, We only need to use it once, as the wrapper of whole App.

Use this code in Routes.js file:

<Switch>
    <Route path={`${this.props.match.path}/dashboard`} component={withRouter(Dashboard)} />
    <Route path={`${this.props.match.path}/batterytable`} component={withRouter(BatteryTable)} />
</Switch>

Suggestion :

Since you are rending Auth and AppMain with route path directly, so you don't need to use withRouter . These components will directly get all the router props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM