【问题标题】:Error while creating a private route for the admin dash board为管理仪表板创建私有路由时出错
【发布时间】:2022-11-05 04:21:59
【问题描述】:

我尝试了下面的代码来私有路由管理仪表板 我正在使用 react-router-dom:6.2.2。我需要帮助来确定只能由管理员访问的私有路由。我尝试了 stackoverflow 中的所有现有解决方案。

应用程序.js

    <BrowserRouter>
<Routes>
    <Route path="/admin/dashboard" element={<PrivateRouter><Dashboard /> </PrivateRouter>} />
   </Routes>
    </BrowserRouter>

私有路由器.js

        <Route
          {...rest}
          component={(props) => {
            const token = window.localStorage.getItem("userInfo");
            console.log(token)
            if (token) {
              return <Component {...props} />;
            } else {
              return <Navigate to={"/login"} />;
            }
          }}
        />
      );
    }

及其在控制台上的抛出错误

index.tsx:24 Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
    at invariant (index.tsx:24:1)
    at Route (index.tsx:235:1)
    at renderWithHooks (react-dom.development)

【问题讨论】:

  • 该错误准确地解释了出了什么问题
  • 但即使我不能使用 <Private Router path="/admin/dashboard" element={<Dashboard />} /> } 也找不到任何其他解决方案
  • 在提问时,解释你需要什么,你尝试了什么,你得到了什么。您做了其中两个,但也请添加您需要的内容,这可能有助于您的问题快速得到答案

标签: reactjs


【解决方案1】:

路由器保护功能:

const routerGuard = () => {
  const token = window.localStorage.getItem("userInfo")
  return !!token // if token exist, return true, else return false
}

您在app.js 中的路线

<Route path="/admin/dashboard" element={routerGuard() ? <Dashboard /> : <Navigate replace to="/login" />} />

【讨论】:

    【解决方案2】:

    如果您只想在设置了令牌的情况下显示管理页面,那么只需使用条件返回方法。

    你的路线应该很简单

    <Route path="/admin/dashboard" element={<Dashboard />} />
    

    您不需要 PrivateRoute 组件。

    在您的仪表板中使用以下内容:

    import { useNavigate } from "react-router-dom"; // import this in your component
    
    function Dashboard(props) {
    const [data, setData] = useState(); // this is data you want to render
     const navigate = useNavigate(); // use this to navigate to your login
    const [ready, setReady] = useState(false) // use this if you want to render data after fetching from end point or it will throw an error of undefined.
     useEffect(() => {
        // here is the logic to check your jwt
        const token = window.localStorage.getItem("userInfo");
        console.log(token)
        if (token) {
            getData(); //get the data and render the page
        } else {
             // nothing is render and user are redirected to your login page
             navigate("/login");
         }
     }, []);
    
    // fetch data you want to display, or skip if you are using hardcoding or a context
    const getData = () {
      // fetch data
      .then(data => { // use this in your fetch method
         setData(data);
         setReady(true);
      });
    }
    return (
      <>
       {ready && <div>
         {data.whatever}
       </div>
      </>
    );
    }
    

    【讨论】:

      【解决方案3】:

      您可以在 react-router-dom 中将 PrivateRoute 作为布局,

      import { Outlet } from "react-router-dom"
      
      const PrivateRoute = ()=>{
        
        const [isLoading, setIsLoading] = useState(true);
        const [isAuthenticated, setIsAuthenticated] = useState(false);
      
        useEffect(()=>{
          const token = window.localStorage.getItem("userInfo");
          if(token){
            setIsAuthenticated(true)
          }
        },[])
        
        if(isLoading){
          return <Loader />
        }
        
        return isAuthenticated? <Outlet /> : <Navigate to="<YOUR_LOGIN_PATH>" /> 
      }
      

      PrivateRoute 可用于包装私有组件。

      【讨论】:

        【解决方案4】:

        要解决您的问题,您需要更改 PrivateRouter.js。

        const PrivateRoutes = ({ children }) => {
         const token = window.localStorage.getItem("userInfo");
                console.log(token)
                if (token) {
                  return <Component {...props} />;
                } else {
                  return <Navigate to={"/login"} />;
                }
        };
        
        export default PrivateRoutes;

        我希望这会有所帮助。队友的欢呼声。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-03-25
          • 2014-11-24
          • 1970-01-01
          • 2017-10-26
          • 2018-09-07
          • 1970-01-01
          • 2018-07-10
          相关资源
          最近更新 更多