提问人:Aslan 提问时间:11/13/2023 最后编辑:Aslan 更新时间:11/13/2023 访问量:47
类方法/异步问题?
issue with class methods / async?
问:
在我的 React 项目中使用 Zustand,我正在定义全局身份验证状态,如您在代码片段中看到的那样。我还定义了一个 Auth API 来运行 auth 方法。但是,出于某种奇怪的原因,即使响应状态为 200 并且当我进入检查时,该行后面的 if-block 行也不会运行,这意味着:不运行。 也不运行。
如果我把它们放在 之前,它们都会运行。if (response.status === 200)
this.setLogin
success=true
console.log("authenticated")
this.setLogin
Zustand商店:
import { create } from "zustand";
type AuthStore = {
id: number | null;
isLoggedIn: boolean;
accessToken: string;
setLogin: (token: string, id: number) => void;
setLogout: () => void;
test: () => void;
};
export const useAuthStore = create<AuthStore>((set) => ({
id: null,
isLoggedIn: false,
accessToken: "",
setLogin: (token, id) =>
set({ isLoggedIn: true, accessToken: token, id: id }),
setLogout: () => set({ isLoggedIn: false, accessToken: "", id: null }),
test: () =>
set((state) => {
console.log(state.accessToken);
return {};
}),
}));
身份验证 API:
import { AxiosResponse, isAxiosError } from "axios";
import { UserAccountType } from "../types/userInfo.type";
import api from "./api";
import { useAuthStore } from "../store/authStore";
interface User {
token: string;
id: number;
}
export class AuthApi {
private static setLogin(token: string, id: number): void {
useAuthStore().setLogin(token, id);
}
static async login(userCred: Partial<UserAccountType>) {
let success = false;
let errorMessage = "";
try {
const response = await api.post<User>("/auth/login", userCred, {
withCredentials: true,
});
if (response.status === 200) {
const token = response.data.token;
const id = response.data.id;
this.setLogin(token, id);
console.log("authenticated");
success = true;
}
} catch (err) {
if (isAxiosError(err)) {
const status = err.response?.status;
console.log(err);
switch (status) {
case 401:
errorMessage =
"Invalid Email or Password. Try again or click Forgot password to reset it.";
break;
default:
errorMessage = `${err.message}. Please try again.`;
}
}
}
return { success, errorMessage };
}
}
答: 暂无答案
评论
static
class
AuthApi
this
login
login
this
AuthApi.setLogin
this.#setLogin