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

React useContext中setScore函数的TypeScript类型定义问题

React Context中setScore的TypeScript类型匹配问题

你遇到的核心问题是useState生成的更新函数类型,和你自定义的Context类型不兼容。useState返回的setScore类型是React.Dispatch<React.SetStateAction<Score>>,它支持两种调用方式:直接传入新的Score对象,或者传入一个接收当前状态并返回新状态的回调函数;而你之前定义的(score: Score) => void只支持第一种调用方式,因此会触发类型不匹配错误。

解决步骤

  1. 修正Context类型定义:直接复用React内置的Dispatch和SetStateAction类型,结合自定义的Score类型来定义setScore的类型。
  2. 调整Context默认值:让默认的setScore函数符合新的类型要求。

修正后的完整代码

import React from "react";

export type RootStackParamList = {
  Home: undefined;
  ReactQuiz: undefined;
};

type Score = {
  correct: number,
  incorrect: number
}

// 修正Context类型,对齐useState返回的更新函数类型
export type ReactQuizContextType = {
  score: Score;
  setScore: React.Dispatch<React.SetStateAction<Score>>;
}

// 调整默认值的setScore,符合Dispatch类型要求
export const ReactQuizContext = React.createContext<ReactQuizContextType>({
  score: {
    correct: 0,
    incorrect: 0
  },
  setScore: () => {}
})

export const useReactQuizContext = () => React.useContext(ReactQuizContext);

说明

  • React.SetStateAction<Score>允许你传入Score对象,或者(prevState: Score) => Score的回调函数,完美匹配useState返回的更新函数的调用方式。
  • React.Dispatch是对这个更新函数的类型封装,确保Context的类型和useState生成的更新函数类型完全对齐。

之后在Provider中传入useState生成的状态和更新函数时,就不会再有类型错误:

const [score, setScore] = React.useState<Score>({
  correct: 0,
  incorrect: 0,
});

// 在Provider中正常传入值
<ReactQuizContext.Provider value={{ score, setScore }}>
  {/* 子组件内容 */}
</ReactQuizContext.Provider>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:31:09