【问题标题】:History.push doesn't work in nested child navbar componentHistory.push 在嵌套的子导航栏组件中不起作用
【发布时间】:2019-04-04 13:50:37
【问题描述】:

我有一个类似下面的应用:

  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>

然后在 App 组件中我有以下内容:

<Layout>
        <Route exact path='/' component={Home} />
        <Route path='/methodmembers/'  component={MethodMembers} />
</Layout>

在 Layout 组件中我有一个子 NavMenu 组件:

 return (
        <Grid fluid>                     
           <NavMenu/>
        </Grid>
)

我的问题: 在 Layout 组件中,当我使用 withRouter 执行以下操作时:

const { history } = this.context.router;
      e.preventDefault();
      history.push('/methodmembers/');

它工作正常,它将我重定向到所需的路线。 但是,在 NavMenu 组件内部,同样的事情不会将我重定向到另一条路线,它只是更新 url。 我正在尝试使用Router,但它仍然无法正常工作。 有谁知道如何解决这个问题?谢谢

【问题讨论】:

  • 您的NavMenu 也是BrowserRouter 组件的子组件吗?
  • 包含布局等的整个 App.js 是 的子级
  • 如果 NavMenu 不在 BrowserRouter 中,则它无法接收历史道具
  • 我们根本没有使用 BrowserRouter。那么 this.context.router 怎么能在 Layout 中工作而在 NavMenu 中却没有呢?

标签: reactjs react-router


【解决方案1】:

您应该将道具传递给 NavMenu,例如:

 return (
    <Grid fluid>                     
       <NavMenu {...this.props}/>
    </Grid>
)

或者您可以尝试使用Router 导出这两个组件:

export default withRouter(Layout);

...

export default withRouter(NavMenu);

并通过以下方式推送路线:

this.props.history.push('/methodmembers/');

【讨论】:

  • 我试过了,但它只是像以前一样更新网址
  • 尽量不要使用上下文,而是使用this.props.history,我已经更新了答案
  • 这也不会重定向我。我不知道为什么上下文在布局中起作用
猜你喜欢
  • 1970-01-01
  • 2021-11-12
  • 2015-09-09
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多