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

React+TS创建Context遇类型不兼容错误,请求技术协助

问题解决:React+TS Context类型不匹配错误

问题原因

你的错误核心是类型不匹配:

  • GiftsType里定义的setChoices是接收两个字符串数组的函数类型(arr1: string[], arr2: string[]) => void
  • 但你传给Provider的setGifts是React useState返回的dispatch函数,类型是Dispatch<SetStateAction<GiftsType>>,两者完全不兼容
  • 另外你错误地把setChoices放进了useState的状态里,这完全没必要——状态只需要存储需要被管理的数据,更新函数不属于状态的一部分

修正后的代码

import { createContext, useState, ReactNode } from 'react';

// 拆分类型:状态数据类型和Context提供的接口类型
type GiftsState = {
  choices: string[];
  links: string[];
};

type GiftsContextType = GiftsState & {
  setChoices: (arr1: string[], arr2: string[]) => void;
};

export const GiftsContext = createContext<GiftsContextType>({
  choices: [],
  links: [],
  setChoices: () => {},
});

// 给children添加上类型
export function GiftsProvider({ children }: { children: ReactNode }) {
  // useState只存储状态数据,不需要包含更新函数
  const [gifts, setGifts] = useState<GiftsState>({
    choices: [],
    links: [],
  });

  // 自定义符合类型要求的setChoices函数
  const setChoices = (arr1: string[], arr2: string[]) => {
    setGifts({
      choices: arr1,
      links: arr2,
    });
  };

  return (
    <GiftsContext.Provider value={{ ...gifts, setChoices }}>
      {children}
    </GiftsContext.Provider>
  );
}

关键修改点

  • 拆分了GiftsState和GiftsContextType,职责更清晰:前者是纯状态数据,后者是Context对外暴露的接口(数据+更新函数)
  • 移除了useState里的setChoices,状态只保留需要管理的choices和links
  • 自定义了setChoices函数,严格符合你定义的类型,内部调用setGifts来更新状态
  • 给GiftsProvider的children添加上了ReactNode类型,符合TS规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:35:51