[英]React JS <Navigate /> not woking
我正在检查用户是否具有“管理员”角色,然后他们可以访问受保护的“/home”路由,否则他们应该被重定向回“/”路由。 但是,当非管理员用户访问“/home”路由时,他们不会被重定向回“/”。
应用程序.js
import "./App.css";
import React from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import Landing from "./components/Landing";
import PhoneDetails from "./components/PhoneDetails";
import Home from "./components/Home/App.jsx";
import Signup from "./components/Signup";
import SignIn from "./components/Signin";
import ForgotPassword from "./components/ForgotPassword";
import { auth } from "./firebase-config.js";
import { useEffect } from "react";
import FirebaseData from "./firebaseData";
function App() {
// getting the user data from firebase
const firebaseData = FirebaseData();
const [displayName, setDisplayName] = React.useState("");
const [isAuthenticated, setIsAuthenticated] = React.useState(false);
const [role, setRole] = React.useState("");
useEffect(() => {
if (firebaseData) {
auth.onAuthStateChanged((user) => {
if (user) {
// User is signed in
// ...
setIsAuthenticated(true);
setDisplayName(user.displayName);
setRole(firebaseData.users?.[user.uid]?.role);
} else {
// User is signed out
// ...
setIsAuthenticated(false);
setDisplayName("");
setRole("");
}
});
}
}, [firebaseData]);
return (
<Routes>
<Route
path="/"
exact
element={
<Home
isAuthenticated={isAuthenticated}
displayName={displayName}
role={role}
/>
}
/>
<Route path="/signup" element={<Signup />} />
<Route path="/signin" element={<SignIn />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
// ERROR ON THIS LINE
{role === "admin" && (
<Route
path="/home"
element={
isAuthenticated && role === "admin" ? (
<Landing />
) : (
<Navigate replace to="/" />
)
}
/>
)}
<Route
path="/details"
element={
isAuthenticated && role === "admin" ? (
<PhoneDetails />
) : (
<Navigate replace to="/" />
)
}
/>
<Route path="/" element={<Navigate replace to="/" />} />
</Routes>
);
}
export default App;
我尝试为此使用 Navigate,但它不起作用。 我知道这可能是一个新手错误,但我不明白为什么他们没有被重定向到“/”路线。 任何帮助表示赞赏!
你能这样试试吗
<BrowserRouter>
<Routes>
<Route path="/" exact element={<div>Default route</div>}></Route>
{role === "admin" && (
<Route
path="/home"
element={
isAuthenticated && role === "admin" ? (
<div>Success page</div>
) : (
<Navigate replace to="/" />
)
}
/>
)}
</Routes>
</BrowserRouter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.