【问题标题】:React onRouteChange对路由变化做出反应
【发布时间】:2017-06-09 02:25:42
【问题描述】:

我试图让我的 Header 组件在 Route 更改时呈现。 我尝试在 Switch 上使用 onChange 和 onValueChange ,但都没有被调用。 有没有办法在路由改变时调用函数?

<Switch>
  <Route path="/posts/new" component={PostsNew}/>
  <Route path="/posts/:id" component={PostsShow}/>
  <Route exact path="/" component={PostsIndex}/>
</Switch>

【问题讨论】:

  • 添加处理程序以侦听路由器,然后创建存储以保存上次状态并在发生时发送自定义事件
  • 这可能适用于旧版本的 react 路由器。我正在使用 3.10.10

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


【解决方案1】:

在浏览了 React Router 文档 (https://reacttraining.com/react-router/web/api/withRouter) 之后,我找到了解决方案。

要在路由更改时更新我的​​标头组件,我所要做的就是导入 withRouter:

import {withRouter} from 'react-router-dom';

并使用 withRouter 导出类:

export default withRouter((connect(null, mapStateToProps)(Header)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2020-05-18
    • 2019-02-01
    • 2021-06-06
    相关资源
    最近更新 更多