【问题标题】:Setting initial route with react-router使用 react-router 设置初始路由
【发布时间】:2016-07-09 21:06:36
【问题描述】:

我有一个关于使用 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”仍然为真,重定向再次发生,导致重定向循环。

我想知道解决此问题的最佳方法是什么?任何帮助是极大的赞赏。提前致谢!

【问题讨论】:

    标签: reactjs react-router react-router-redux


    【解决方案1】:

    添加索引路由,然后在挂载时重定向如何?

    <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'); 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      相关资源
      最近更新 更多