反应 ProtectedRoute问题/未能按预期工作

问题描述 投票:0回答:1

我正在使用一些受保护的路由制作React应用程序。直到我添加Switch包装器,然后/ about和/ contact路由都无法显示,它才能正常工作。

您能解释为什么会这样吗?如果需要在此处切换?

const PrivateRoute = ({ component: Component, path, rootModel }) => {
  return (
    <Route
      exact
      path={path}
      render={(props) => {
        loginCheck();
        return (
          <>
            {rootModel.auth.isLoggedIn ? (
              <Component {...props} rootModel={rootModel} />
            ) : (
              <Redirect to='/login' />
            )}
          </>
        );
      }}
    />
  );
};

const Routes = ({ rootModel }) => {
  return (
    <Router history={history}>
      <Switch>
        <Route path='/login' component={Login} />

        <PrivateRoute path='/' component={Main} rootModel={rootModel} />
        <PrivateRoute path='/about' component={About} rootModel={rootModel} />
        <PrivateRoute path='/about' component={About} rootModel={rootModel} />
        <PrivateRoute
          path='/contact'
          component={Contact}
          rootModel={rootModel}
        />
      </Switch>
    </Router>
  );
};

export default Routes;
node.js reactjs
1个回答
0
投票

只需在不返回任何内容之前进行登录检查,就像这样:

const PrivateRoute = ({ component: Component, path, rootModel }) => {
  const isLogged = loginCheck();
  if (rootModel.auth.isLoggedIn) {
      return (
    <Route
      exact
      path={path}
      render={(props) => {
        loginCheck();
        return (
              <Component {...props} rootModel={rootModel} />
            )}
          </>
        );
      }}
    />
  );
  } else {
       return <Redirect to={} />
  }

};
© www.soinside.com 2019 - 2024. All rights reserved.