简体   繁体   English

@reach/router 嵌套保护路由

[英]@reach/router nested protected route

I use reach/router with custom protected route like this :我使用具有自定义保护路线的到达/路由器,如下所示:

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>

i want this to be nested route with user/:id我希望这是带有user/:id嵌套路由

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

what should i do?我该怎么办?

I Feel like you're complicating things我觉得你把事情复杂化了


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>
  )
}

In case this didn't work as intended or you feel you want to use it in your way, do this如果这没有按预期工作,或者您想以自己的方式使用它,请执行此操作


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

No need of using ProtectedRoute HOC for UserDetail since it's already nested under ProtectedRoute无需为UserDetail使用ProtectedRoute HOC,因为它已经嵌套在ProtectedRoute

and in UserList use props.children to render UserDetail并在UserList使用props.children来呈现UserDetail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM