我正在尝试在两个带有标题的单独列表中渲染一些 React 组件。为此,我使用 bool 值来确定哪个组件进入哪个列表。
这就是我的代码的样子:
const children1: List<SomeComponent> = List([
bool1 && <SomeComponent key="0" />,
bool2 && <SomeComponent key="1" />,
]).filter(value => value !== false);
const children2: List<SomeComponent> = List([
!bool1 && <SomeComponent key="0" />,
!bool2 && <SomeComponent key="1" />,
]).filter(value => value !== false);
这工作得很好,但 Flow 不明白我在创建列表后过滤掉了 false
值,只包含 SomeComponent
值:
bool1 && <SomeComponent key="0" />,
^^^^^ boolean. This type is incompatible with
const children1: List<SomeComponent> = List([
^^^^^^^^^^^^^^^^^^^ prototype
使用标准 JavaScript 数组时也会发生这种情况:
const children2: Array<SomeComponent> = [
!bool1 && <SomeComponent key="0" />,
!bool2 && <SomeComponent key="1" />,
].filter(value => value !== false);
我可以做什么来帮助 Flow 了解正在发生的事情?
最佳答案
此特定情况的可能解决方法是不在列表中使用 bool 值而是使用 null:
const children2: List<SomeComponent> = List([
!bool1 ? <SomeComponent key="0" /> : null,
!bool2 ? <SomeComponent key="0" /> : null,
].filter(Boolean));
当过滤不可变而不是内部数组时它不起作用,但这似乎与this issue有关.
关于javascript - Flow 无法识别过滤不可变列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042789/