所以,我有一些工作代码,但我只是觉得有一种解决方案,我可以只使用一个 .map() 但我没有看到它。
这些组件不是 sibling (它们不共享相同的父组件),因此为了解决这个问题,我只是对同一对象数组执行了 .map() 两次,但我觉得这是浪费资源,并且对于这种情况必须有更好的解决方案。
这是代码
<div className="pricepoints-form">
<Tabs className="tabs">
<TabList>
{
this.state.pricepointsData.map(pricepoint => (
<Tab className="tab">{pricepoint.name}</Tab>
))
}
</TabList>
{
this.state.pricepointsData.map(pricepoint => (
<TabPanel>
<Pricepoint
pricepoint={pricepoint}
displayLast4={this.state.displayLast4}
/>
</TabPanel>
))
}
</Tabs>
</div>
最佳答案
Can using
.map()
twice over the same array be avoided even though the components the map() renders are not siblings?
从技术上来说,是的,这是可能的。但让我们看看您真正优化的是什么。
map
本质上是一个 for
循环,它将值分配给新数组:
// example
function map(transform) {
const ret = []
for (let i = 0; i < this.length; i++) {
ret.push(transform(this[i], i, this))
}
return ret
}
这意味着您可以将 map 函数替换为您自己的函数,该函数运行循环并创建两个数组:
function myMap(transform1, transform2) {
const r1 = []
const r2 = []
for (let i = 0; i < this.length; i++) {
r1.push(transform1(this[i], i, this))
r2.push(transform2(this[i], i, this))
}
return [r1, r2]
}
使用这个新功能充其量也很尴尬:
const [tabs, panels] = myMap.call(this.state.pricepointsData, pricepoint => (...), pricepoint => (...))
...
<TabList>
{ tabs }
</TabList>
{ panels }
...
所以真正的问题应该是:这个抽象值得吗?
对此我有一个反问:
2x1 和 1x2 哪个更大?
您可以使用两个循环,每个循环执行一项操作(2 个 map
调用),也可以使用一个循环执行两项操作(1 个 myMap
调用)。
关于javascript - 即使 map() 渲染的组件不是同级组件,是否可以避免在同一数组上使用 .map() 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50321820/