React.Children.map vs React Children.toArray.map

时间:2017-06-23 12:43:11

标签: javascript reactjs

在React children中是组合中使用的不透明数据结构。为了对其进行处理,React公开了React.Children API,其中包含方法React.Children.mapReact.Children.toArray

根据文档,Children.map在每个子元素上调用一个函数(通常是渲染,或cloneElement),而toArray从不透明children更改为一个简单的js数组。

React.Children.map(child, fn)React.Children.toArray.map(child, fn)感觉实际上是等效的。我经常看到使用了Children.map,并且正在寻找可靠的证据来备份最佳做法,或者对toArray.map的用例进行解释。

我的第一直觉是toArray显然会添加另一个调用,这可能会降低性能(稍微?),但我相信toArray也会删除undefinednull儿童。

3 个答案:

答案 0 :(得分:2)

这是一个非常古老的问题,但我正在添加我发现的内容!

在将 Children.toArrayChildren.map 作为子项传递时,

nullundefined 有点不同。

<ReactComponent>
  <div>one</div>
  { null }
</ReactComponent>

在上面的例子中,

Children.toArray 跳过 nullundefined,结果的 length 将是 1

然而 Children.map(children, (val) => {}) 也会在 null 时迭代,结果的 length 将是 2

答案 1 :(得分:1)

根据the react codeChildren.toArray与传递身份函数Children.map的{​​{1}}相同。因此(x) => x总是比调用Children.map(children, func)更高效。

答案 2 :(得分:1)

如果您使用的是 Inline If with Logical && Operator,那么 React.Children.mapReact.Children.toArray.map 之间的区别非常重要

假设你有这个 React 组件

const ReactComponent = () => {
    return (
        React.Children.map((child, index) => (
            <div>{child}</div>
        ))
    )
}

const checkBooleanValue() => {
    return false;
}

您将其与子项和条件 If 一起使用:

<ReactComponent>
        <span>Child</span>
        {checkBooleanValue() &&
            <span>Another Child</span>
        }
</ReactComponent>

如果 checkBooleanValue()false

  • React.Children.map 会给你两个孩子
    • <span> React.Element
    • false 用于内联 If
  • React.Children.toArray.map 只会给你一个孩子:
    • <span> React.Element

使用 React.Children.map,您最终会为第二个孩子获得一个空的 div。

相关问题