React Router v6 错误:[PrivateRoute] 不是
使用 React Router v6 并创建私有路由时,开发人员可能会遇到错误,指出“[PrivateRoute] 不是
问题的根源
当“PrivateRoute”组件未正确渲染时会出现此错误作为“
解决方案
要解决此问题,请确保将 PrivateRoute 组件定义为 Routes 组件中 Route 组件的嵌套子组件,如下所示:
<code class="javascript">// PrivateRoute.js import React from "react"; import { Navigate, Outlet } from "react-router-dom"; const PrivateRoute = () => { const auth = null; // Determine if authorized // Return outlet if authorized, navigate to login otherwise return auth ? <Outlet /> : <Navigate to="/login" />; }; // App.js import React, { Fragment } from "react"; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; import Navbar from "./components/layout/Navbar"; import Home from "./components/pages/Home"; import Register from "./components/auth/Register"; import Login from "./components/auth/Login"; import PrivateRoute from "./components/routing/PrivateRoute"; const App = () => { return ( <Router> <Fragment> <Navbar /> <Routes> <Route exact path="/" element={<PrivateRoute />}> <Route exact path="/" element={<Home />} /> </Route> <Route exact path="/register" element={<Register />} /> <Route exact path="/login" element={<Login />} /> </Routes> </Fragment> </Router> ); };</code>
在此修改后的代码中:
以上是为什么我在 React Router v6 中收到'[PrivateRoute] 不是组件”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!