当所有路由根据条件动态加载时如何重定向到路由?

时间:2021-05-20 21:40:13

标签: reactjs react-router react-router-dom

这是我根据上下文中的用户对象加载路由(react router dom 5)的代码。

function App() {
  return (
      <UserContextProvider>
        <BrowserRouter>
          <Navigation/>
        </BrowserRouter>
      </UserContextProvider>
  );
}

导航代码。这里我有条件地加载路由。

function Navigation() {

  const { contextState } = useUserContext();

  const routes = contextState.user ? routesAuthenticated : routerUnauthenticated;
  
  return (
    <Switch>
        {routes.map((route, index) => {
            return (
                <Route
                    key={index}
                    path={route.path}
                    exact={route.exact}
                    render={(props: RouteComponentProps) => (
                        <route.component name={route.name} {...props} {...route.props} />
                    )}
                />
            );
        })}
    </Switch>
  );
}

您会看到,我根据上下文用户对象加载了不同的路由。 路由是简单的配置文件:

export const routerUnauthenticated: IRoute[] = [
  {
    path: '/register',
    name: 'Register page',
    component: RegisterPage,
    exact: false,
  },
  {
      path: '/login',
      name: 'Login page',
      component: LoginPage,
      exact: false,
  }...

问题是我在路线 http://localhost:3000/login 上,成功登录后,我看到路线 http://localhost:3000/login 的空白页面。 在登录之前,我有 3 条路线登录/注册/主页。 登录后,我有 5 条路线仪表板/配置文件... 我想要做的是在成功登录后到达 /dashboard 路线,但由于我的想法是动态路线加载,我无法弄清楚如何导航。

在我的上下文中,登录是一个简单的假函数:

try {
        setContextState({ type: ContextActions.LOGIN_IN_PROGRESS });

        setTimeout(() => {console.log({ userId: 1, username: 'admin@admin.com' });
          setContextState({ type: ContextActions.LOGIN_SUCCESS, payload: { user: { userId: 1, username: 'admin@admin.com' } } });
        }, 3000);
      } catch(error) {
        setContextState({ type: ContextActions.LOGIN_ERROR });
      }

2 个答案:

答案 0 :(得分:2)

为什么不直接加载所有路由? 您可以使用自定义 Route 组件来查看 contextState.user 是否存在 有点像受保护的路由,如果未通过身份验证的用户转到该路由,则会重定向到 /login 或 /register。

答案 1 :(得分:1)

这是被广泛使用的最常见的 protectedRoute 组件。

const App = () => {
    const { user } = useAuth();
  return (
    <Router>
        <Route path="/public">
          <Public />
        </Route>
        <Route path="/login">
          <Login />
        </Route>
        <PrivateRoute path='/protected' user={user}>
          <Protected />
        </PrivateRoute>
      </div>
    </Router>
  )
}

const PrivateRoute = ({ children, user, ...rest }) => (
    <Route {...rest} render={({ location }) => {
      return user === null
        ? <Redirect to={{
            pathname: '/login',
            state: { from: location }
          }}
        />
        : children
    }} />
)