简体   繁体   English

React路由器dom不渲染子组件但url已更改

[英]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. 我有子路由,当我试图改变AppMain.js中的路由时,它改变了url但是组件没有被渲染,而是现有的组件被重新渲染。 But if I am doing the same history.push inside Dashboard or BatteryTable the route is working fine. 但是,如果我在DashboardBatteryTable执行相同的history.push,路由工作正常。

App.js App.js

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

AppMain.js AppMain.js

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

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

Routes.js 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. 因为你使用Router组件两次,将它从Routes.js文件中删除,我们只需要使用它一次,作为整个App的包装器。

Use this code in Routes.js file: Routes.js文件中使用此代码:

<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 . 由于您直接使用路径路径重新授予Auth和AppMain,因此您不需要使用withRouter These components will directly get all the router props. 这些组件将直接获取所有路由器道具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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