使用受保护路由的嵌套路由无法正常工作

Nested routing using protected routes is not working properly

之前我发过一个类似的问题:

我试图在 protectRoute.tsx:

中实现受保护的路由
import { Navigate, Outlet } from "react-router";
import { RootStateOrAny, useSelector } from "react-redux";

interface ProtectRouteProps {}

export default function ProtectRoute(props: ProtectRouteProps) {
  const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
  const { userInfo } = userSignin;

  return userInfo?.user?.isAdmin ? <Outlet /> : <Navigate to='/' />;
}

我真的不知道 ProtectRouteProps 是什么以及我应该在其中放入什么。同样在路由部分,我确实像他告诉我的那样:

<Route path='/createItem' element={<ProtectRoute />} />
<Route path='/createItem' element={<CreateItem />} />

现在的问题是无法访问CreateItem,因为ProtectRoute 页面是空的。我该怎么办?

I don't really know what ProtectRouteProps is and what I should put in it.

没有道具。用法很清楚:

<Route path='/createItem' element={<ProtectRoute />} />

没有道具传递给 ProtectRoute。您可以删除道具对象:

import { Navigate, Outlet } from "react-router";
import { RootStateOrAny, useSelector } from "react-redux";

export default function ProtectRoute() {
  const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
  const { userInfo } = userSignin;

  return userInfo?.user?.isAdmin ? <Outlet /> : <Navigate to='/' replace />;
}

The problem now is that can't access CreateItem because is going on the ProtectRoute page that is an empty one. What should i do?

“Auth”路由就是所谓的 layout routes。他们应用一些逻辑,也许是一些样式化的布局 CSS,并为要渲染到的嵌套 Route 组件渲染一个 Outlet。嵌套的 Route 组件使用 path 属性进行路由匹配。

示例:

<Route element={<ProtectRoute />}>
  <Route path='/createItem' element={<CreateItem />} />
  ... other protected routes ...
</Route>
 <Route exact path='/Login' element={<Login name="Login Page"></Login>}></Route>
    <Route element={<Protected/>}> 
    <Route exact path='/' element={<Home/> }></Route>
    <Route exact path='/Content' element={<Content />}></Route>
    </Route>

   <Route path='*' element={<Login/>} ></Route>
  </Routes>

创建Protected.js

import { Navigate, Outlet } from 'react-router-dom';

   const useAuth = ()=>{
    if(localStorage.getItem("isLogged")){
    const user = {loggedIN :true};
    return user && user.loggedIN
    }else{
    const user = {loggedIN :false};
    return user && user.loggedIN
   }

 }

 const Protected = () => {
 const isAuth = useAuth();
 return isAuth ? <Outlet/>:<Navigate to={"/login"}/>
 }

export default Protected