React Router Dom,受保护的路由,得到ProtectedRoute不是路由

React Router Dom, protected route, getting ProtectedRoute is not a route

我在我的应用程序中创建了 auth.js 文件和 ProtectedRoute.js 文件。在 API 中使用 JWT 创建了一个令牌并在登录我的应用程序时存储在本地存储中。在我的 app.js 中导入了 Authprovider 和 ProtectedRoute,它在路由中显示错误。请检查我的代码并告诉我哪里出错了

auth.js

  import { useContext, createContext } from "react";

  const AuthContext = createContext(null)

  export const AuthProvider=({ children })=>{

  const keyToken = localStorage.getItem("token");
  const user = localStorage.getItem("name");
  const userid = localStorage.getItem("id");
  const pimg = localStorage.getItem("profile");

  return(
         <AuthContext.Provider value={{ keyToken,user,userid,pimg}}> {children} 
         </AuthContext.Provider>
      )
    } 

   export const useAuth = () => {
           return useContext(AuthContext)
     }

protectedRoute.js

import React from "react";
import { Navigate , Route } from "react-router-dom";
import {useAuth} from "./auth"

function ProtectedRoute({ component: Component, ...restOfProps }) {

  const auth=useAuth();
  const isAuthenticated = auth.keyToken;
  console.log("this", isAuthenticated);
 

  return (
    <Route
      {...restOfProps}
      render={(props) =>
        false ? <Component {...props} /> : <Navigate  to="/login" />
      }
    />
  );
}

export default ProtectedRoute;

App.js

import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Login from "./components/SignIn";
import Category from "./pages/Category";
import Addcategory from "./pages/Addcategory";
import Subcategory from "./pages/Subcategory";
import Dashboard from "./pages/Dashboard";
import { Profile } from "./components/Profile";
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { AuthProvider} from "./components/authentication/auth";
import ProtectedRoute from "./components/authentication/protectedRoute";

function App() {
  return (
    <AuthProvider>
    <Router>
      <Routes>
          <Route exact path='/' element={< Login />}></Route>
          <Route exact path='/login' element={< Login />}></Route>
         <ProtectedRoute exact path='/dashboard' element={ Dashboard}/>
         {/*<Route exact path='/dashboard' element={< Dashboard />}></Route>*/}
          <Route exact path='/category' element={< Category />}></Route>
          <Route exact path='/categoryAdd' element={< Addcategory />}></Route>
          <Route exact path='/subcategory' element={< Subcategory />}></Route>
         <Route exact path='/profile' element={< Profile />}></Route> 
      </Routes>
      <ToastContainer />
    </Router>
    </AuthProvider>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

export default App;

控制台中显示错误:

虽然您为 ProtectedRoute 所做的工作我认为适用于 React Router Dom 版本 5,但版本 6 略有不同。这是一种方法(查看库团队制作的 example 以了解更多信息):

App.js:

function App() {
  return (
    <AuthProvider>
    <Router>
      <Routes>
          <Route exact path='/dashboard' element={ <ProtectedRoute/>}/>
      </Routes>
      <ToastContainer />
    </Router>
    </AuthProvider>
  );
}

ProtectedRoute.js:

function ProtectedRoute() {

  const auth=useAuth();
  const isAuthenticated = auth.keyToken;

  if(isAuthenticated){
    return <Dashboard/>
  }
  return (
    <Navigate  to="/login" />
   );
}

export default ProtectedRoute;

您有 react-router-dom v5v6 的混合代码 您可以阅读迁移指南 upgrading from v5

可以使用 OutletProtectedRoute 渲染为布局。检查这个 example

// ProtectedRoute.js
import { Navigate, Outlet } from 'react-router-dom';

export const ProtectedRoute = () => {
  const location = useLocation();
  const auth = useAuth();

  return auth.isAuthenticated
    ? <Outlet />
    : <Navigate to="/login" state={{ from: location }} replace />;
};

// App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";

function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/" element={<ProtectedRoute /> }>
            <Route path='dashboard' element={<Dashboard />} />
            <Route path='category' element={<Category />} />
            // rest of your code
          </Route>
        </Routes>
        <ToastContainer />
      </BrowserRouter>
    </AuthProvider>
  );
}