类方法/异步问题?

问题描述 投票:0回答:1

在我的 React 项目中使用 Zustand,我定义了全局身份验证状态,如代码片段中所示。我还定义了一个 Auth API 来运行 auth 方法。但是,由于某些奇怪的原因,即使响应状态为 200 并且当我将其纳入

if (response.status === 200)
检查时,
this.setLogin
行之后的 if 块行也不会运行,这意味着:
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 };
  }
}
javascript reactjs async-await static-methods zustand
1个回答
0
投票

请参阅调用静态方法

无法使用非静态方法中的

this
关键字直接访问静态成员。您需要使用类名来调用它们:
CLASSNAME.STATIC_METHOD_NAME()
或通过将方法作为构造函数的属性调用:
this.constructor.STATIC_METHOD_NAME()

因此请使用以下任意一种:

this.constructor.setLogin(token, id)
// or
AuthApi.setLogin(token, id)
© www.soinside.com 2019 - 2024. All rights reserved.