【问题标题】:General route interceptors for react-routerreact-router 的通用路由拦截器
【发布时间】:2016-03-20 07:44:40
【问题描述】:

用户登录后,在完成个人资料之前无法继续。如果用户尝试导航到其他页面,只要他们的个人资料完整,我想拦截他们并将他们重定向回个人资料页面。目前我想出的最佳解决方案是:

render() {
  if (!profileComplete()) {
    return document.location.assign(document.location.origin + '/complete-prof'));
  }
  return <Page />;
}

虽然这确实有效,但似乎不正确,因为您应该从 render 返回一个有效组件。

我也在componentWillMountcomponentDidMount 中尝试过这样做。这也有效,但是您可以在重定向发生之前看到另一个页面的闪光。

这是一个小问题,但我还必须在所有需要拦截的页面上包含这个拦截,而不是通过一些配置或更通用的方法来处理它。

在使用 React 视图时,是否有首选方法来阻止/拦截路由?

【问题讨论】:

    标签: reactjs react-router refluxjs


    【解决方案1】:

    这个Lifecycle Mixin怎么样

    routerWillLeave 方法可以阻塞路由

    但是如果你想在用户想要进入其他页面时重定向到配置文件组件之外,你可能需要在 标签中添加一个 onEnter:onEnter of Route

    // check login 
    function auth(next, replace) {
        let isLogin = Auth.isLogin();
        if (next.location.pathname === '/login' && isLogin) {
            replace(null, '/');
        } else if (next.location.pathname !== '/login' && !isLogin) {
            replace(null, '/login');
        }
    };
    document.addEventListener('DOMContentLoaded', function () {
        ReactDOM.render((
            <Router onUpdate={onPathChange} history={history}>
                <Route path='/' component={App} onEnter={auth}>
                    <IndexRedirect to='index' />
                    <Route path='index' component={Index} />
                    <Route path="category" component={Category} />
                    <Route path="attribute" component={Attribute} />
                </Route>
                <Route path='login' component={Login} onEnter={auth} />
            </Router>),
          appElement
        );
    });
    

    【讨论】:

    • Lifecycle mixin 已弃用,所以我宁愿不使用它。一般来说,React 中的 Mixins 似乎不受欢迎。你能告诉我更多关于redirect at outside of the profile component 的意思吗?
    • 我的意思是在路由配置中设置重定向,就像上面的代码一样,它是一个检查登录重定向。当配置文件未完成时,将 onEnter 添加到要重定向的路由。如果你想这样做,你必须检查组件外部的配置文件完成。
    猜你喜欢
    • 2017-08-30
    • 2016-11-12
    • 2015-10-11
    • 2018-12-25
    • 2011-11-22
    • 1970-01-01
    • 2019-03-27
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多