2017-06-09 26 views
0

我試圖讓我的Header組件在路由改變時呈現。 我嘗試在交換機上使用onChange和onValueChange,但都沒有人被調用。 有沒有辦法在路由改變時調用一個函數?React onRouteChange

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

添加處理程序以偵聽路由器和然後創建商店以保存最後狀態並在發生自定義事件時發送 –

+0

這可能適用於舊版本的反應路由器。我正在使用3.10.10 – FIL1994

回答

0

通過陣營路由器文檔(https://reacttraining.com/react-router/web/api/withRouter)挖後,我發現的溶液。

爲了讓我的頭組件更新時的路線改變了所有我需要做的就是進口withRouter:

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

和導出類使用withRouter:

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