我使用反應路由器的歷史useQueries(createHashHistory)()
和我有幾條路線,我想阻止導航到基於路線的配置。
所以路由的配置是這樣的:反應路由器:防止導航到目標路線
<Route path="/" name={RouteNames.APP} component={AppContainer}>
<Route path="view-1"
onEnter={ view1onEnter }
onLeave={ view1onLeave }
component={ View1 }
canNavigate={ false }
/>
<Route path="view-2"
onEnter={ view2onEnter }
onLeave={ view2onLeave }
component={ View2 }
canNavigate={ true }
/>
...
</Route>
因此,讓我們假設我在#/view-2
並調用一個動作像history.push({pathname: '/view-1'});
。但只要路線view-1
有一個標誌canNavigate={false}
- 我想阻止導航到它,並顯示一條消息而不更改散列和任何其他副作用(如調用鉤onLeave
)。
我在想聽history
:
history.listenBefore((location, callback) => {
//e.g. callback(false) to prevent navigation
})
,但我不能讓路由的實例來檢查canNavigate
標誌。
後來我發現,history
有一個方法match
這實際上獲取基於下一個路由器的狀態給出location
:
history.listenBefore((location, callback) => {
history.match(location, (error, redirectLocation, nextState) => {
const route = _.last(nextState.routes);
if (route.canNavigate) {
callback();
} else {
callback(false);
}
});
})
但問題是,history.match
電話onLeave
鉤view-2
內(其可以,例如,即使用戶停留在view-2
視圖中,也會清除狀態)。
問題:是它可以防止view-2
導航無任何變化,在所有歷史/路由器以及基於目標的路由配置這個決定?
嗯,實際上它[可以](https://github.com/reactjs/react-router/blob/v2.1.0/docs/guides/ConfirmingNavigation.md)。問題是我有很多路線,並希望擺脫檢查重複。 – Kiril
通過重複,你的意思是你不想檢查狀態,如果它可以導航,因爲每個路線已經有canNavigate道具?另一件事,canNavigate道具是動態的還是靜態的? –
@JohnWilliamDomingo,'canNavigate'可以是任何東西。在我的特殊情況下 - 這是一個靜態屬性。是的,你是對的重複。 – Kiril