1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
我沒(méi)有看到組件history中定義的位置Login。此外,您還設(shè)置了 cookie,但isAuthenticated僅在App組件安裝時(shí)設(shè)置,以后絕不會(huì)更新。
您可以傳遞回調(diào)來(lái)Login更新?tīng)顟B(tài),并在重新渲染和重新渲染具有重新封閉狀態(tài)的路由App時(shí)讓重定向自然發(fā)生。它還已經(jīng)嘗試專(zhuān)門(mén)匹配和渲染路線(xiàn),因此將您的路徑從最具體到最不具體排序,并且您不需要將 prop 添加到每個(gè)路線(xiàn)。AppisAuthenticatedSwitchexact
應(yīng)用程序
function App() {
const [isAuthenticated, setAuthenticated] = useState(false);
useEffect(() => {
if (cookie.get("authorization")) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
}, []);
return (
<Router>
<Switch>
<PrivateRoute
path="/user/:id"
component={UserDetail}
auth={isAuthenticated}
/>
<PrivateRoute
path="/createuser"
component={CreateUser}
auth={isAuthenticated}
/>
<PrivateRoute
path="/home"
component={ListUser}
auth={isAuthenticated}
/>
<Route path="/">
{isAuthenticated ? (
<Redirect to="/home" />
) : (
<Login setAuthenticated={setAuthenticated} /> // <-- pass callback
)}
</Route>
</Switch>
</Router>
);
}
登錄
function Login({ setAuthenticated }) { // <-- destructure prop
const loginUser = (body) => {
SetLoader(true);
fetch("/api/v2/users/tokens", {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json"
}
})
.then((response) => {
if (response.status == 200) {
SetError(false);
cookie.set("authorization", response.headers.map.authorization, {
path: "/"
});
setAuthenticated(true); // <-- set authenticated
} else {
SetError(true);
StoreResponse(JSON.parse(response._bodyInit).message);
}
})
.catch((error) => {
console.error("Error:", error);
})
.finally(() => {
SetLoader(false); // <-- set loading false in finally block
});
};
...
}
添加回答
舉報(bào)