访问 StackOverflow 的所有开发人员您好,我在使用受保护的路由时遇到问题,它给出了 [ProtectedRoute] 不是组件的错误。的所有子组件必须是 a 或
const adminUsers = [
{username:'admin', password:'admin'}
...etc
]
const ProtectedRoute = ({ element, ...rest }) => {
const isAuthenticated = localStorage.getItem('user');
const isAdmin = adminUsers.some(user => user.username === isAuthenticated);
const renderFunction = (props) => {
if (isAuthenticated && isAdmin) {
return element; // Render the protected route element
} else {
return <Navigate to="/login" replace state={{ from: props.location }} />; // Redirect with location state
}
};
return <Route {...rest} render={renderFunction} />;
};
export default ProtectedRoute;
import { BrowserRouter, Link, Route, Routes, Router } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import Register from './pages/Register';
import BookingCar from './pages/BookingCar';
import AddCar from './pages/AddCar';
import Admin from './pages/Admin';
import EditCar from './pages/EditCar';
import ProtectedRoute from './components/ProtectedRoute';
import UserBookings from './pages/userBookings';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<ProtectedRoute path="/booking/:carid" element={<BookingCar />} />
<ProtectedRoute path="/userbookings" element={<UserBookings />} />
<ProtectedRoute path="/addcar" element={<AddCar />} />
<ProtectedRoute path="/editcar/:carid" element={<EditCar />} />
<ProtectedRoute path="/admin" element={<Admin />} />
</Routes>
</BrowserRouter>
);
}
export default App;
我尝试了多种方法来解决它,但总是给我这个错误。
这就是 v5 保护路由的方式。对于 v6,您实际上需要使用
Route
:
<Route
path="home"
element={
<ProtectedRoute>
<Home />
</ProtectedRoute>
}
/>
const ProtectedRoute = ({children}) => {
const canUserAccess = /* some logic *.
if(!canUserAccess) {
return <Navigate to={"/login"}/>
}
return <>{children}</>
}