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

React集成Flow报错:属性为Prop却被要求存在于State中

问题分析与解决

嘿,我一眼就揪出问题所在了——你把React.Component的泛型参数顺序写反啦!

核心错误原因

React组件的类型声明规则是React.Component<Props, State>:第一个泛型参数是组件接收的Props类型,第二个才是组件自身的State类型。

你在Other组件里写成了React.Component<State, Props>,这直接搞混了Flow的类型识别逻辑:它把你定义的Props类型当成了组件的State类型,把空的State类型当成了Props类型。所以才会出现“number必须存在于State中”的诡异报错——Flow误以为number是Other组件的State属性,而不是传入的Props。

修正后的代码

1. 修复Other组件的泛型顺序

import * as React from 'react';
type Props = {
  number: number,
}
type State = { }
// 泛型参数顺序改为 <Props, State>
class Other extends React.Component<Props, State> {
  render() {
    const { number } = this.props;
    return (
      <div className="container">
        {number}
      </div>
    );
  }
}

2. 同步修复Example组件的问题(它也存在泛型顺序错误+缺失render方法)

import * as React from 'react';
type Props = { }
type State = {
  number: number,
  cards: Array<{suit: string} | {rank: number}>,
}
// 修正泛型顺序,同时补上render方法
class Example extends React.Component<Props, State>{
  render() {
    return <Other number={this.state.number} />;
  }
}

补充说明

修正后Flow就能正确识别:number是Other组件接收的只读Props,而不是它自身的State属性。你之前的困惑完全是因为泛型参数顺序搞反,导致Flow的类型检查逻辑被带偏了,才出现了看似不合理的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:58:47