如何在React中使用useRoutes钩子创建私有路由。

huangapple go评论66阅读模式
英文:

How to do private routes with the useRoutes hook in React

问题

我正在尝试在React中构建私有和公共路由我正在使用useRoutes钩子我不知道如何做到这一点在Stack Overflow上已经存在了对这个问题的答案然而那只是一些代码的复制粘贴我真的很想学会如何做到这一点

我尝试使用了另一个答案但并没有对我有太多帮助如果有人能帮忙我将非常感激这是我写的代码

```jsx
import { useRoutes } from "react-router-dom"
import Home from "../pages/home"
import Items from "../pages/itens"
import Login from "../pages/login"
import Printers from "../pages/printers"
import { AuthContext } from "../contexts"
import { useContext } from "react"
import { Navigate } from "react-router-dom"

function Routes() {

    const { sessionContextValue } = useContext(AuthContext)
    const { isAuth } = sessionContextValue

    const routes = [
        {
            path: '/',
            element: isAuth ? <Home /> : <Navigate to={'/login'} replace/>,
        },
        {
            path: '/printers',
            element: <Printers />
        },
        {
            path: '/items',
            element: <Items />
        },
        {
            path: '/login',
            element: <Login />
        }
    ]

    let router = useRoutes(routes)
    return router
}

export default Routes
英文:

I'm trying to build a private and public route in React, and I'm using the useRoutes hook. I didn't know how to do this, already exist an answer to this question on Stack Overflow. However, it was just a copy and paste of some code. I really want to really learn how I can afford this.

I tried using the other answer, but it didn't help me much. If anyone can assist, I would be extremely grateful. This is the code I wrote.

import Home from &quot;../pages/home&quot;
import Items from &quot;../pages/itens&quot;
import Login from &quot;../pages/login&quot;
import Printers from &quot;../pages/printers&quot;
import { AuthContext } from &quot;../contexts&quot;
import { useContext } from &quot;react&quot;
import { Navigate } from &quot;react-router-dom&quot;

function Routes() {

    const { sessionContextValue } = useContext(AuthContext)
    const { isAuth } = sessionContextValue

    const routes = [
        {
            path: &#39;/&#39;,
            element: isAuth ? &lt;Home /&gt; : &lt;Navigate to={&#39;/login&#39;} replace/&gt;,
        },
        {
            path: &#39;/printers&#39;,
            element: &lt;Printers /&gt;
        },
        {
            path: &#39;/items&#39;,
            element: &lt;Items /&gt;
        },
        {
            path: &#39;/login&#39;,
            element: &lt;Login /&gt;
        }
    ]

    let router = useRoutes(routes)
    return router
}

export default Routes

答案1

得分: 0

使用useRoutes钩子来创建私有和公共路由,你可以使用一个自定义组件来检查用户的身份验证状态,并呈现适当的元素或重定向到登录页面。例如,你可以创建一个名为PrivateRoute的组件,如下所示:

import { Navigate, useLocation } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../contexts";

export default function PrivateRoute({ element }) {
  const { sessionContextValue } = useContext(AuthContext);
  const { isAuth } = sessionContextValue;
  const location = useLocation();

  return isAuth ? (
    element
  ) : (
    <Navigate to="/login" state={{ from: location }} replace />
  );
}

然后,你可以在路由数组中像这样使用这个组件:

import Home from "../pages/home";
import Items from "../pages/items";
import Login from "../pages/login";
import Printers from "../pages/printers";
import { useRoutes } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";

function Routes() {
  const routes = [
    {
      path: "/",
      element: <PrivateRoute element={<Home />} />,
    },
    {
      path: "/printers",
      element: <PrivateRoute element={<Printers />} />,
    },
    {
      path: "/items",
      element: <PrivateRoute element={<Items />} />,
    },
    {
      path: "/login",
      element: <Login />,
    },
  ];

  let router = useRoutes(routes);
  return router;
}

export default Routes;
英文:

To create private and public routes with the useRoutes hook, you can use a custom component that checks the authentication status of the user and renders the appropriate element or redirects to the login page. For example, you could create a PrivateRoute component like this:

import { Navigate, useLocation } from &quot;react-router-dom&quot;;
import { useContext } from &quot;react&quot;;
import { AuthContext } from &quot;../contexts&quot;;

export default function PrivateRoute({ element }) {
  const { sessionContextValue } = useContext(AuthContext);
  const { isAuth } = sessionContextValue;
  const location = useLocation();

  return isAuth ? (
    element
  ) : (
    &lt;Navigate to=&quot;/login&quot; state={{ from: location }} replace /&gt;
  );
}

Then, you can use this component in your routes array like this:

import Home from &quot;../pages/home&quot;;
import Items from &quot;../pages/items&quot;;
import Login from &quot;../pages/login&quot;;
import Printers from &quot;../pages/printers&quot;;
import { useRoutes } from &quot;react-router-dom&quot;;
import PrivateRoute from &quot;./PrivateRoute&quot;;

function Routes() {
  const routes = [
    {
      path: &quot;/&quot;,
      element: &lt;PrivateRoute element={&lt;Home /&gt;} /&gt;,
    },
    {
      path: &quot;/printers&quot;,
      element: &lt;PrivateRoute element={&lt;Printers /&gt;} /&gt;,
    },
    {
      path: &quot;/items&quot;,
      element: &lt;PrivateRoute element={&lt;Items /&gt;} /&gt;,
    },
    {
      path: &quot;/login&quot;,
      element: &lt;Login /&gt;,
    },
  ];

  let router = useRoutes(routes);
  return router;
}

export default Routes;

huangapple
  • 本文由 发表于 2023年7月14日 07:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定