加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 使用react-router设置初始路由

发布时间:2020-12-15 20:12:06 所属栏目:百科 来源:网络整理
导读:我有一个关于使用react-router(与Redux结合)设置初始路由的问题.我已经设置了一些路由并基于我的Redux商店的状态,我需要始终将用户重定向到页面加载的某个路由. 我的路线目前的设置方式如下: Provider store={store} Router history={history} Route path="
我有一个关于使用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’仍然是真的,重定向再次发生,导致重定向循环.

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读