You need to enable JavaScript to run this app. React使用useReducer与useContext时报TS2554:期望0参数却传入1个
优惠活动
大模型
产品
解决方案
定价
更多

React使用useReducer与useContext时报TS2554:期望0参数却传入1个

问题根因
  • 你没有给useReducer显式传入泛型参数,TypeScript无法正确推导出dispatch函数可接收Action参数,错误认为dispatch不接受任何入参
  • 各文件之间的类型定义没有统一导出引用,类型推导链路断裂
  • initialState、AuthState接口、authContextType三者的字段可选性、类型定义不匹配,进一步干扰了类型推导
修复步骤

步骤1:统一导出公共类型

修改AuthReducer.tsx,将内部定义的Actions和AuthState类型导出,方便其他文件引用:

// AuthReducer.tsx 新增类型导出
export type Actions =
  | {
      type: 'USER_LOADED';
      payload: {
        name: string;
        id: string;
      };
    }
  | {
      type: 'AUTH_ERROR';
      payload?: string;
    }
  | {
      type: 'LOGIN_SUCCESS';
      payload: { token: string };
    }
  | {
      type: 'LOGIN_FAIL';
      payload: string;
    }
  | {
      type: 'LOGOUT';
      payload?: string;
    }
  | {
      type: 'CLEAR_ERRORS';
    };

export interface AuthState {
  token?: string | null;
  isAuthenticated?: boolean | null;
  loading: boolean;
  user?: {
    name: string;
    id: string;
  } | null;
  error?: string | undefined | null;
}

// reducer的state参数类型调整为AuthState,类型定义更统一
const AuthReducer = (
  state: AuthState,
  action: Actions
): AuthState => {
  // 原有业务逻辑保持不变
};

步骤2:给useReducer显式指定泛型

修改AuthState.tsx,导入导出的AuthState和Actions类型,给useReducer传入泛型约束:

// AuthState.tsx 新增导入
import AuthReducer, { AuthState, Actions } from './AuthReducer';

// 修改useReducer调用,显式传入泛型
const [state, dispatch] = useReducer<(state: AuthState, action: Actions) => AuthState>(AuthReducer, initialState as AuthState);

步骤3:修正AuthContext的类型匹配

修改AuthContext.tsx,调整authContextType的字段类型,和实际状态匹配:

// AuthContext.tsx 修改authContextType
type authContextType = {
  loadUser: () => Promise<void>;
  login: (formData: {
    email: string;
    password: string;
  }) => Promise<void>;
  logout: () => void;
  clearErrors: () => void;

  error: string | null;
  isAuthenticated: boolean | null;
  loading: boolean;
  user: {
    name: string;
    id: string;
  } | null;
  token: string | null;
};

// 初始化context时用类型断言匹配
const authContext = createContext<authContextType>(initialState as authContextType);

完成以上三步后,dispatch的类型会被正确识别,TS2554报错会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:03:01