我在前端使用 React
,后端使用 Node.js
,数据库使用 Postgre
。
我创建了自己的 API 来验证用户并使用 useState
和 useContext
钩子来存储用户的登录状态。
我还在成功登录后设置了重定向功能,但是 useState
需要一段时间来更新用户的登录状态,因此页面没有被重定向。
我在从服务器获取数据时尝试使用 async
和 await
,但在对用户进行身份验证时仍然存在延迟。
我也尝试关注一些博客,例如 this
此上下文状态处理登录功能并更新组件内的登录状态。
import React, { createContext, useContext, useState } from "react";
import { GlobalContext } from "./GlobalState";
export const LoginAuth = createContext();
export const ProvideAuth = ({ children }) => {
const auth = useProvideAuth();
return <LoginAuth.Provider value={auth}>{children}</LoginAuth.Provider>;
};
export const useAuth = () => {
return useContext(LoginAuth);
};
const useProvideAuth = () => {
const [user, setUser] = useState(null);
const { setIsLogin } = useContext(GlobalContext);
const login = async (userDetails) => {
const response = await fetch("http://localhost:4000/api/v1/login/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(userDetails),
}).catch((err) => console.log(err.message));
const data = await response.json();
if (data?.error) {
setUser(false);
} else {
setUser(data);
setIsLogin(true);
}
};
return { user, login };
};
此状态用于更新整个应用程序的登录状态
import React, { createContext, useState } from "react";
export const GlobalContext = createContext();
export const GlobalProvider = ({ children }) => {
const [isLogin, setIsLogin] = useState(false);
return (
<GlobalContext.Provider value={{ isLogin, setIsLogin }}>
{children}
</GlobalContext.Provider>
);
};
私人路线代码
import React, { useContext } from "react";
import { Redirect, Route } from "react-router";
import { GlobalContext } from "../State/GlobalState";
const PrivateRouteLogin = ({ children, ...rest }) => {
const { isLogin } = useContext(GlobalContext);
return (
<Route
{...rest}
render={({ location }) => {
return isLogin ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location },
}}
></Redirect>
);
}}
/>
);
};
export default PrivateRouteLogin;
答案 0 :(得分:0)
您可以为 loginStatus 设置另一个值
false = not logged in
true = logged in
pending = for collect all data
在这种情况下,您可以在您的网站上显示背景(正在加载),直到检测到 loginStatus