javascript - Flow 无法识别过滤不可变列表

标签 javascript immutable.js flowtype

我正在尝试在两个带有标题的单独列表中渲染一些 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/

相关文章:

javascript - 来自 JSON 数据的邻接列表

javascript - Angular JS : Unordered List Elements not getting displayed

redux - Redux 状态下的数组列表

javascript - 如何自定义外部流类型定义文件

node.js - 如何从 npm 发布的模块中导入流注解、类型和接口(interface)

javascript - 如何让我的内容 2 最初隐藏,然后从右侧滑入?

javascript - "li"行内元素的高度

webpack - 如何让 Flow 与 Vue 2 (webpack) 一起正常工作?

javascript - 不可变js : How to deserialise a complex JS object

javascript - 仅使用与先前嵌套键不匹配的新数据更新不可变列表?