【问题标题】:Problem with private router in react app in React Router v6React Router v6 中的反应应用程序中的私有路由器问题
【发布时间】:2022-01-24 22:20:56
【问题描述】:

一切都适用于较低版本,但不适用于 v6 版本。我浏览了许多与 v6 的私有路由相关的文章,但没有成功。

在 app.js 文件中

<ProtectedRoute exact path="/account" component={Profile} />

在 ProtectedRoute.js 文件中

import React, { Fragment } from "react";
import { useSelector } from "react-redux";
import { Redirect, Route } from "react-router-dom";

const ProtectedRoute = ({ isAdmin, component: Component, ...rest }) => {
  const { loading, isAuthenticated, user } = useSelector((state) => state.user);

  return (
    <Fragment>
      {loading === false && (
        <Route
          {...rest}
          render={(props) => {
            if (isAuthenticated === false) {
              return <Redirect to="/login" />;
            }

            if (isAdmin === true && user.role !== "admin") {
              return <Redirect to="/login" />;
            }

            return <Component {...props} />;
          }}
        />
      )}
    </Fragment>
  );
};

export default ProtectedRoute; 

【问题讨论】:

    标签: node.js reactjs mern


    【解决方案1】:

    他们实际上让它变得更容易了。

    如果您查看example on their doc,您会看到他们是如何做到的

    试试这样的:

    // ProtectedRoute
    import React, { FC } from "react";
    import { Navigate } from "react-router-dom";
    
    const ProtectedRoute: FC = ({auth, children }) => {
      if (!auth) {
        return <Navigate to="/login" />;
      }
      return <div>{children}</div>;
    };
    
    export default ProtectedRoute;
    
    
    

    【讨论】:

    • 还不行。
    猜你喜欢
    • 2022-01-11
    • 2022-01-17
    • 1970-01-01
    • 2022-01-09
    • 2017-10-05
    • 2022-01-19
    相关资源
    最近更新 更多