【问题标题】:Redirecting user based on state in React根据 React 中的状态重定向用户
【发布时间】:2016-03-29 16:30:52
【问题描述】:

现在,我的路由器是这样的:

<Router history={browserHistory}>
    <Route component={Provider}>
        <Route path="/" component={AppPage}>
            <Route path="login" component={LoginPage}/>
            <Route component={LoggedinPage}>
                <Route path="onboarding" component={OnboardingPage}/>
                <Route component={OnboardedPage}>
                    <IndexRoute component={HomePage}/>
                    <Route path="settings" component={SettingsPage}/>
                </Route>
            </Route>
        </Route>
    </Route>
</Router>

LoggedinPage 重定向到/login,如果用户没有登录,OnboardedPage 重定向到/onboarding,如果用户没有完成入职流程(选择用户名等)。但是,我认为将来可能需要更多这些条件重定向。处理这些条件重定向的最佳方法是什么?是否可以有一个组件来处理所有重定向?

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

&lt;Route&gt;s 接受路由匹配时调用的onEnter 钩子。钩子看起来像这样:

function requireAuth(nextState, replace) {
    if (!loggedIn()) {
        replace({ pathname: 'login' });
    }
}

然后像这样使用它:

<Route path="/" component={AppPage}>
    <Route path="home" component={HomePage} onEnter={requireAuth}/>
    <Route path="login" component={LoginPage}/>
</Route>

一个更可组合的示例,让您可以组合多个检查:

function checkAuth() {
    if (!loggedIn()) {
        return { pathname: 'login' };
    }
}

function checkOnboarding() {
    if (!completedOnboarding()) {
        return { pathname: 'onboarding' };
    }
}

function redirect(...checks) {
    return function(nextState, replace) {
        let result;
        checks.some(check => {
            result = check();
            return !!result;
        });
        result && replace(result);
    };
}

然后组合起来!

<Route path="/" component={AppPage}>
    <Route path="home" component={HomePage}
        onEnter={redirect(checkAuth, checkOnboarding)}/>
    <Route path="login" component={LoginPage}/>
    <Route path="onboarding" component={OnboardingPage}
        onEnter={redirect(checkAuth)}/>
</Route>

【讨论】:

  • +1,这是一个好方法,唯一困扰我的是替换刷新整个窗口,这不包含在 SPA 样式中。
【解决方案2】:

你可以有一个函数来检查用户是否登录,然后导入它:

import {browserLocation} from './browser-location'
export default function checkLoggedIn() {
    if (localStorage.jwt === null)
        browserLocation.pushState('/login')
}

【讨论】:

  • 我必须以这种方式手动解析 URL 对吧?就像我需要if (localStorage.jwt === null &amp;&amp; !window.location.pathname.match(/^\/login(\/|$)/))有没有办法做到这一点并且仍然使用 React Router 来解析 URL?
  • 我重新回答了。因此,您只需导入此函数并在要路由到的组件的渲染部分中调用它。
猜你喜欢
  • 2022-09-29
  • 2021-09-13
  • 1970-01-01
  • 2017-06-14
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多