1

我使用具有自定义保护路由的到达/路由器,如下所示:

const ProtectedRoute = ({ component: Component, ...rest }) => (
  localStorage.getItem('user_id') ? <Component {...rest} /> : <Redirect from="" to="/login" noThrow />
);

const LoginRoute = ({ component: Component, ...rest }) => (
  localStorage.getItem('user_id') ? <Redirect from="" to="/home" noThrow /> : <Component {...rest} />
);

const PublicRoute = ({ component: Component, ...rest }) => (
  <Component {...rest} />
);

<Router>
  <LoginRoute component={Login} path="/login" />
  <PublicRoute default component={Notfound} />

  <ProtectedRoute component={landingPage} path="/home" />
  <ProtectedRoute path="/" component={App} />
  <ProtectedRoute component={UserList} path="user" />
  <ProtectedRoute component={UserDetail} path="user/create" />
</Router>

我希望这是嵌套路由user/:id

<ProtectedRoute component={UserList} path="user" />
<ProtectedRoute component={UserDetail} path="user/create" />

我应该怎么办?

4

1 回答 1

4

我觉得你把事情复杂化了


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

  useEffect(() => {
    localStorage.getItem('user_id') && setLoggedIn(true)
  }, [])

return (
  <Router>
    <LoginRoute component={Login} path="/login" />
    <Notfound default />

    {
      loggedIn 
      ? (
        <>
         <LandingPage path="/home" />
         <App path="/" component={App} />
         <UserList component={UserList} path="user">
           <UserDetail component={UserDetail} path="create" />
         </UserList>
        </>
       ) : (
        <Redirect from="" to="/login" noThrow />
       )
      }
     </Router>
  )
}

如果这没有按预期工作,或者您觉得您想以自己的方式使用它,请执行此操作


<Router>
  ...
  <ProtectedRoute component={UserList} path="user">
    <UserDetail path="create" />
  </ProtectedRoute>
</Router>

不需要使用ProtectedRouteHOC,UserDetail因为它已经嵌套在ProtectedRoute

UserList用于props.children渲染UserDetail

于 2020-03-12T07:51:04.110 回答