使用react-router设置初始路由

5
我有一个关于使用react-router(与Redux结合)设置初始路由的问题。我已经设置了几个路由,并根据来自Redux存储的状态,需要在页面加载时始终将用户重定向到某个特定的路由。
目前我的路由设置如下:
<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”得到满足并重定向到“/thanks”时,由于onEnter传递给了根路由,redirectToInitialRoute再次被触发。由于“anotherCondition”仍为真,重定向会再次发生,导致重定向循环。我想知道解决这个问题的最佳方法是什么?非常感谢您的帮助。提前致谢!
1个回答

5
如何添加索引路由并在挂载时重定向?
<Provider store={store}>
    <Router history={history}>
        <Route path="/" component={App} onEnter={redirectToInitialRoute}>
            <IndexRoute component={Welcome} />          
            <Route path="/send" component={OverviewPage} />
            <Route path="/thanks" component={ConfirmPage} />
            <Route path="/:categoryIdentifier" component={CategoryPage} />
        </Route>
    </Router>
</Provider>

然后在你的欢迎组件中:

componentDidMount: function () {
    if (condition) { 
        browserHistory.push('/here'); 
    } else { 
        browserHistory.push('/there'); 
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接