【问题标题】:React Native SectionList has incomprehensible flow type errorReact Native SectionList 有无法理解的流类型错误
【发布时间】:2018-03-17 10:28:06
【问题描述】:

如果我的代码中有这个简单的SectionList 定义:

const s = (
  <SectionList
    renderItem={({ item }) => <Text>abc</Text>}
    renderSectionHeader={({ section }) => <Text>abc</Text>}
    sections={[{ data: [1, 2, 3], title: 'abc' }]}
  />
);

并且流程生成此错误消息,它引用整个“标签块”(实际上是从 VSCode 复制粘贴):

[flow] props of React element `SectionList` (This type is incompatible with See also: React element `SectionList`)

这里发生了什么?

编辑我正在使用

flow-bin: 0.56.0
react: 16.0.0
react-native: 0.49.1

EDIT2 所以这个例子可以简化为这个简单的行(不影响错误信息):

<SectionList sections={[]} />;

EDIT3 我刚刚发现流程抱怨 React Native 库中定义的几种类型(主要是缺少泛型类型的类型参数)。我想知道是否应该使用较旧的 flow-bin 版本。有 React Native 和 flow 的兼容性表吗?

【问题讨论】:

  • 您使用的是哪个版本的 react-native? react-native 的代码包含 Flow 注释,因此您可以通过查看 SectionList 的代码来准确了解它的预期:github.com/facebook/react-native/blob/…
  • 是的......好吧,我仍然不知道。但是,我添加了库版本号。
  • react-native 的 0.49-stable 分支使用 ^0.53.0 作为其 flow-bin 依赖版本。尝试恢复到 v0.53.0。 github.com/facebook/react-native/blob/0.49-stable/package.json
  • 我试过了,还是出现错误信息。但是,该应用程序可以完美运行。因此,以后我将忽略此错误消息。

标签: list react-native flowtype


【解决方案1】:

react-native: 0.49.3flow-bin: 0.53.0 也有类似的问题。从SectionList 源检查类型定义后,让它在没有类型警告的情况下工作,如下所示:

type Row = {
  name: string,
}

type Section = {
  title: string,
  data: $ReadOnlyArray<Row>,
}

const mySections: $ReadOnlyArray<Section> = [...] // your data here

<SectionList sections={mySections} />

所以对我来说关键是使用$ReadOnlyArray&lt;T&gt; 而不是Array&lt;T&gt;。也许这对你有帮助!

【讨论】:

  • 这对我没有任何改变。
【解决方案2】:

React 有一个名为 SectionBase 的部分的内置 Flow 类型:

import type { SectionBase } from 'react-native/Libraries/Lists/SectionList'
type Section = SectionBase<DataType>

所以根据 Martin 的回答,你会写:SectionBase&lt;Row&gt;

【讨论】:

    【解决方案3】:

    OP 的代码应该没有收到 Flow 的投诉,因为它是有效的。

    我遇到了一个相关问题,因为我正在使用包含部分的状态,但我找不到适合 Flow 的类型。我无法直接使用 SectionBase,因为它没有我需要的额外 title 属性。我通过使用交叉类型解决了它:

    type Section = { title: string } & SectionBase<ScheduleChange>
    type State { sections: Section[] }
    
    ...
    
    <SectionList
        sections = this.state.sections
        ...
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2017-11-12
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多