当无状态组件大写时,Flow + React中断

问题描述 投票:0回答:2

What works

我正在尝试编写无状态组件。以下代码工作,流程说它没关系:

import React, { type Node } from 'react';

function renderCond({children}: {children: Array<[boolean, ?Node]>}): ?Node {
  for (const [bool, Component: ?Node] of children) {
    if (bool) {
      return Component;
    }
  }
  return null;
}

<renderCond>
  {[
    [false, <h1>{'Comp 1'}</h1>],
    [true, <h1>{'Comp 2'}</h1>],
    [true, <h1>{'Comp 3'}</h1>],
  ]}
</renderCond>

What doesn't

但是,如果我用“RenderCond”搜索并替换“renderCond”,流程就会爆炸。为什么?

3: function RenderCond({children}: {children: Array<[boolean, ?Node]>}): ?Node {
                                                                         ^
all branches are incompatible: Either null or undefined [1] is incompatible with null [2]. Or property `@@iterator` is missing in null or undefined [1] but exists in `$Iterable` [3].

References:
3: function RenderCond({children}: {children: Array<[boolean, ?Node]>}): ?Node {
                                                                         ^ [1]
[LIB] ..//static/v0.93.0/flowlib/react.js:14:   | null
                                                  ^ [2]
[LIB] ..//static/v0.93.0/flowlib/react.js:20:   | Iterable<?React$Node>;
                                                  ^ [3]

它适用于我return Component || null并且不使用可选的返回类型,但我仍然不明白为什么我必须这样做。如果有一个可选类型,并且我正在返回那个可选的东西,为什么流程会抱怨所有分支都不兼容?

即使我return Component || null没有改变返回类型,流量仍然是错误。

当我在flow --show-all-branches本地运行时,流程列出了更多的分支。为什么未定义不在列表中?

TryFlow链接

reactjs flowtype
2个回答
0
投票

null组件写成JSX风格时,流程系统以不同方式推断RenderCond

null被推断为可迭代的React$Node,不应该被暗示为可选的返回类型。

RenderCond({children}: {children: Array<[boolean, ?Node]>}): Node {}

0
投票

函数组件必须返回React$Node的子类型,该子类型不包含void

© www.soinside.com 2019 - 2024. All rights reserved.