我正在尝试编写无状态组件。以下代码工作,流程说它没关系:
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>
但是,如果我用“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
本地运行时,流程列出了更多的分支。为什么未定义不在列表中?
当null
组件写成JSX风格时,流程系统以不同方式推断RenderCond
。
null
被推断为可迭代的React$Node
,不应该被暗示为可选的返回类型。
RenderCond({children}: {children: Array<[boolean, ?Node]>}): Node {}
函数组件必须返回React$Node
的子类型,该子类型不包含void
。