为什么无法在 Router 中使用 protectRoute?

Why unable to use protectRoute inside Router in react?

我有一个反应应用程序,用户只有在 login/signup 之后才能访问主页。 我已经使用 protectRoutes 来实现它,但是我在 Router 组件中收到以下错误:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

app.js 文件的代码:

import {useState} from 'react'
import './App.css';
import {Routes,Route,Link} from 'react-router-dom'
import SignupPage from './Pages/SignupPage';
import LoginPage from './Pages/LoginPage';
import Homepage from './Pages/Homepage';
import PrivateRoute from "./Pages/PrivateRoute";
import {HashRouter as Router} from 'react-router-dom'
function App() {
  const [username,setUsername]=useState("");
  const [currentUser,setCurrentUser]=useState({});
  return (
    <Router>
    <div className="App">
     <Route path="/" exact element={<SignupPage></SignupPage>}/>
     <Route path="/signup" exact element={<SignupPage currentuser={currentUser} setcurrentuser={setCurrentUser} setusername={setUsername}></SignupPage>}/>
     <Route path="/login" exact element={<LoginPage></LoginPage>}/>
     <PrivateRoute path="/homepage" exact currentuser={currentUser} element={<Homepage user={currentUser} username={username} setusername={setUsername}></Homepage>}/>
    </div>
    </Router>

  );
}

export default App;

这是什么错误,我该如何解决?

问题

您正在直接渲染 Route 组件,而不是将它们包装在 Routes 组件中。

解决方案

重构 PrivateRoute 组件以呈现 Outlet 组件而不是 Route 并包装您要保护的路由。

示例:

import { Navigate, Outlet } from 'react-router-dom';

const PrivateRoute = ({ currentuser }) => {
  // auth business logic

  return isAuthenticated
    ? <Outlet />
    : <Navigate to="/login" replace />;
};

...

import { HashRouter as Router, Routes, Route, Link} from 'react-router-dom'

function App() {
  const [username,setUsername]=useState("");
  const [currentUser,setCurrentUser]=useState({});
  return (
    <Router>
      <div className="App">
        <Routes>
          ... unprotected routes ...
          <Route path="/" element={<SignupPage />} />
          <Route
            path="/signup"
            element={(
              <SignupPage
                currentuser={currentUser}
                setcurrentuser={setCurrentUser}
                setusername={setUsername}
              />
            )}
          />
          <Route path="/login" element={<LoginPage />} />
          ...

          <Route element={<PrivateRoute currentuser={currentUser} />}>
            ... protected routes ...
            <Route
              path="/homepage"
              element={(
                <Homepage
                  user={currentUser}
                  username={username}
                  setusername={setUsername}
                />
              )}
            />
            ...
          </Route>
        </Routes>
      </div>
    </Router>
  );
}