【问题标题】:React router dom not rendering child component but url changed反应路由器dom不渲染子组件但url改变了
【发布时间】:2019-08-27 00:43:22
【问题描述】:

我有子路由,当我尝试更改 AppMain.js 中的路由时,它更改了 url 但组件没有被渲染,而是现有组件被重新渲染。但是,如果我在 DashboardBatteryTable 内执行相同的 history.push 操作,则该路线运行良好。

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>

【问题讨论】:

  • 可能是因为你使用了两个路由器 hoc,从 Routes.js 组件中移除,只在 App 组件中使用。此外,当您使用路由路径 withRouter hoc 渲染组件时,也不需要将其删除。
  • @MayankShukla 那么子路由将如何工作?
  • 它会起作用,我们只需要Router 的一个实例,它应该只包装整个应用程序。它将跟踪所有路线和路径的变化。
  • @MayankShukla 您能否将其发布为答案。非常感谢。

标签: reactjs react-router react-router-dom


【解决方案1】:

因为你使用了两次Router组件,把它从Routes.js文件中删除,我们只需要使用一次,作为整个App的包装器。

Routes.js 文件中使用此代码:

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

建议

由于你是直接用路由路径渲染 Auth 和 AppMain,所以你不需要使用withRouter。这些组件会直接获取所有的router props。

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2020-06-21
    • 2017-12-23
    • 2018-07-26
    • 2023-04-03
    相关资源
    最近更新 更多