0

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

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

1 回答 1

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)));
于 2017-06-09T03:06:35.200 回答