You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中createContext默认值与Promise适配问题求助

解决React + TypeScript中AccountContext的类型不匹配与默认值设置问题

问题根源

  1. 你的UserAuthTypes接口要求username和password为必填属性,但AccountContext.Provider的value只传入了authenticate函数,导致类型校验失败。
  2. 默认值写法错误,没有提供符合接口要求的完整默认实现。

解决方案

步骤1:修正Context的类型定义

首先明确Context的核心需求:你需要的是提供认证方法,而非存储登录用的用户名和密码(这两个是认证方法的参数,无需存入Context)。重新定义接口:

// 定义Cognito认证响应的类型(可根据实际返回数据细化)
type AuthResponse = {
  accessToken?: string;
  idToken?: string;
  // 按需添加其他返回字段
};

// 重新定义Context类型
export interface UserAuthContextType {
  authenticate: (username: string, password: string) => Promise<AuthResponse>;
}

如果确实需要在Context中存储用户名/密码(不推荐存储密码,存在安全风险),则将它们设为可选属性:

export interface UserAuthTypes {
  username?: string;
  password?: string;
  authenticate: (username: string, password: string) => Promise<AuthResponse>;
}

步骤2:设置正确的createContext默认值

默认值必须完全匹配接口类型,包括authenticate的默认实现(避免组件调用Context方法时出现未定义错误):

const defaultAuthContext: UserAuthContextType = {
  authenticate: async () => {
    return Promise.reject(new Error("Authenticate method not implemented"));
  }
};

const AccountContext = createContext<UserAuthContextType>(defaultAuthContext);

步骤3:修正Provider的value

现在Provider的value可以直接传入符合类型的authenticate函数:

const Account = (props: { children: React.ReactNode }) => {
  const authenticate = async (username: string, password: string): Promise<AuthResponse> =>
    await new Promise((resolve, reject) => {
      const user = new CognitoUser({
        Username: username,
        Pool: UserPool,
      });

      const authDetails = new AuthenticationDetails({
        Username: username,
        Password: password,
      });

      user.authenticateUser(authDetails, {
        onSuccess: (data) => {
          // 提取需要的认证数据返回
          resolve({
            accessToken: data.getAccessToken().getJwtToken(),
            idToken: data.getIdToken().getJwtToken()
          });
        },
        onFailure: (err) => {
          reject(err);
        },
        newPasswordRequired: (data) => {
          resolve(data);
        },
      });
    });

  return (
    <AccountContext.Provider value={{ authenticate }}>
      {props.children}
    </AccountContext.Provider>
  );
};

额外优化:移除any类型

原来的authenticate?: any存在类型安全隐患,现在明确了函数的参数和返回值类型,代码更健壮。

内容的提问来源于stack exchange,提问作者beepboopiamabot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:55:16