5
我有一個關於使用react-router(與Redux結合)設置初始路由的問題。我已經設置了幾條路線,並基於我的Redux商店的狀態,我需要始終在頁面加載時將用戶重定向到某個路線。使用react-router設置初始路由
我的路線目前正在建立的方法如下:
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App} onEnter={redirectToInitialRoute}>
<Route path="/send" component={OverviewPage} />
<Route path="/thanks" component={ConfirmPage} />
<Route path="/:categoryIdentifier" component={CategoryPage} />
</Route>
</Router>
</Provider>
我已經添加的OnEnter功能,我的根路徑。我這樣做是因爲我總是需要在頁面加載時重定向,而與用戶進入應用程序的頁面無關。順便我的OnEnter功能設置如下:
function redirectToInitialRoute (nextState, replace) {
if (condition) {
replace('/send');
}
else if (anotherCondition) {
replace('/thanks');
}
}
但是這種設置會發生什麼,是(舉例來說)「anotherCondition」滿足並重定向到「/感謝」。由於onEnter在根路由上傳遞,所以redirectToInitialRoute再次被觸發。由於'anotherCondition'仍然成立,重定向會再次發生,從而導致重定向循環。
我想知道什麼是解決此問題的最佳方法?任何幫助是極大的讚賞。提前致謝!