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

使用React Context遇Flow提示number与Number不兼容错误该如何解决

问题根源

Flow类型系统对数值类型做了严格的分层定义:

  • 小写number:对应JS原生的数值原始类型,所有直接书写的数值字面量(比如示例中的0)都属于该类型
  • 大写Number:对应JS的Number包装对象类型,仅指代通过new Number()创建的实例,常规业务开发几乎不会使用该类型

你的代码中类型声明里将index定义为大写的Number类型,但传入createContext的默认值、组件传递的index属性都是原始number类型,两者类型不匹配直接触发了Flow的兼容校验报错。

修复方案

将所有类型定义里大写的Number替换为小写的number即可,修改后的Context文件代码如下:

// @flow
import React, { createContext, useContext } from "react";

export type CountryIndexProviderType = {
  index: number,
};

const CountryContext = createContext<CountryIndexProviderType>({
  index: 0,
});

type CountryContextProviderProps = {
  index: number,
};

const CountryContextProvider = ({ index }: CountryContextProviderProps) => {
  return <CountryContext.Provider value={{ index }}></CountryContext.Provider>;
};

const useCountryIndexContext = () => useContext(CountryContext);

export { CountryContext, CountryContextProvider, useCountryIndexContext };

补充说明:Flow中其他原始类型也遵循相同规则,小写string/boolean对应原生原始类型,大写String/Boolean对应包装对象类型,常规开发统一使用小写即可避免同类报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:15:03