React中实现路由守卫

  • child::

    条件路由

    梗概

    • 使用<Router>组件的render属性来条件性地渲染 <Profile /> 组件或者重定向到首页。

    示例

     <Route
       path="/profile"
       render={() =>
         isAuthenticated ? <Profile /> : <Redirect to="/login" />
       }
     />
    指向原始笔记的链接

  • 使用[use::HOC](Higher Order Component): 通过编写高阶组件来包装需要权限验证的组件,实现更灵活的权限控制。

    const withAuth = (Component) => {
      return (props) => {
        if (权限判断语句) {
          return <Redirect to="/login" />;
        }
        return <Component {...props} />;
      };
    };
     
    const ProtectedRoute = withAuth(ProfilePage);
     
    // 在Route中使用
    <Route path="/profile" component={ProtectedRoute} />