[英]Flow doesn't recognize filtering an immutable List
I'm trying to render some React components in two separate lists with headers. 我正在尝试使用标头在两个单独的列表中呈现一些React组件。 For this I use boolean values to determine which component goes into which list.
为此,我使用布尔值来确定哪个组件进入哪个列表。
This is how my code looks like: 这是我的代码的样子:
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);
This works completely fine, but Flow doesn't understand that I filter out the false
values after creating the list to only have SomeComponent
values in there: 这完全正常,但是Flow不明白我在创建列表之后过滤掉了
false
值,只有SomeComponent
值:
bool1 && <SomeComponent key="0" />,
^^^^^ boolean. This type is incompatible with
const children1: List<SomeComponent> = List([
^^^^^^^^^^^^^^^^^^^ prototype
It also happens when using standard JavaScript Arrays: 使用标准JavaScript数组时也会发生这种情况:
const children2: Array<SomeComponent> = [
!bool1 && <SomeComponent key="0" />,
!bool2 && <SomeComponent key="1" />,
].filter(value => value !== false);
What can I do to help Flow understand what's going on? 我该怎么做才能帮助Flow了解正在发生的事情?
A possible workaround for this specific case is not using boolean in the List but null: 针对此特定情况的可能解决方法是在List中不使用boolean但是null:
const children2: List<SomeComponent> = List([
!bool1 ? <SomeComponent key="0" /> : null,
!bool2 ? <SomeComponent key="0" /> : null,
].filter(Boolean));
It doesn't work when filtering the immutable instead of the inner Array, but this seems to be connected to this issue . 过滤不可变而不是内部数组时,它不起作用,但这似乎与此问题有关 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.