将默认路由反转为私有路由,反之亦然

时间:2019-06-28 06:48:58

标签: reactjs react-router-dom mobx

在我的应用程序中,您只能分别在获得授权后才能进入主页,如果用户未被授权,则登录页面始终是第一页面;如果用户未被授权,则我将具有私有路由,而这是不允许的。到登录页面的常规路径,因为会有很多私有路由,所以我想做一些事情,例如反向路由,即我将使用一次私有路由,而在其他需要授权才能进入该页面的页面上,放置一条普通路线,如何实现?

const PrivateRoute = ({store, component: Component, ...rest}) => {
  return (
     <Route
       {...rest}
       render={(props)=>
        localStorage.getItem("token") ? (
           <Component {...props} />
        ) : (
           <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location },
              }}
            />
         )
       }
    />
 )

 export const Routes = () => {
    return (
       <Switch>
          <Route exact path="/" component={Login} />
          <PrivateRoute path="/homepage" component={Homepage} />
          {/* ...more PrivateRoutes */}
       </Switch>
      );
   };

我需要这样的东西

<PrivateRoute exact path="/" component={Login} />
<Route path="/homepage" component={Homepage} />
{/* ...more Routes*/}```


1 个答案:

答案 0 :(得分:1)

您的主要目标似乎是减少PrivateRouter变量的使用,因此您可以尝试以下方法:对已登录/未登录的用户使用不同的路由

const App = () => {
  const [loggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    // check if user is logged in
  }, []);

  return (
    <Switch>
      {!isLoggedIn ? (
        <>
          <Route exact path="/" component={Login} />
        </>
      ) : (
        <>{/* Routes for logged user*/}</>
      )}
    </Switch>
  );
};
``