Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React.Children.map vs React Children.toArray.map_Javascript_Reactjs - Fatal编程技术网

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

Javascript React.Children.map vs React Children.toArray.map,javascript,reactjs,Javascript,Reactjs,在React中,children是合成中使用的不透明数据结构。要对其进行管理,React会公开React.ChildrenAPI,其中包括React.Children.map和React.Children.toArray方法 根据文档,Children.map在每个子元素上调用一个函数(通常用于渲染,或cloneElement),而toArray则从不透明的Children变为简单的js数组 React.Children.map(child,fn)和React.Children.toArray.

在React
中,children
是合成中使用的不透明数据结构。要对其进行管理,React会公开
React.Children
API,其中包括
React.Children.map
React.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
也会删除
未定义的
null
子项

根据,
Children.toArray
Children.map
传递身份函数
(x)=>x
。因此
Children.map(Children,func)
总是比调用
Children.toArray(Children.map(func)
更有效

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

Children.toArray
与作为子对象传递
null
未定义的
时的
Children.map
有点不同

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

一
{null}
在上面的例子中

Children.toArray
跳过
null
undefined
length
的结果将为
1

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