【问题标题】:How map with function and text ReactJs如何映射函数和文本 ReactJs
【发布时间】:2020-06-19 01:56:11
【问题描述】:

我想解释一下我今天遇到的问题。

目前我的地图,一切正常

我的问题,我希望我可以在其中创建一个 div 以显示总计的结果 ,可惜我做不到

你知道如何解决这个问题吗?

 {this.props.items.map(item => { 
 const product = this.props.items;
 let total = 0;

 console.log(total)
 console.log('yolo',product)
 console.log('yolo array',product[0].quantity)

for (let i = 0 ; i<product.length;i++){
console.log('products',product[i].quantity) 
total = total + product[i].quantity;                        
}
} 
)}

【问题讨论】:

标签: javascript reactjs function dictionary


【解决方案1】:

即使您要使用总计渲染某些内容,使用此方法您也将为props.items 中的每个item 渲染一个“总项目”。你想在这里使用的是reduce 方法。这是一个非常基本的 div 的示例,但您可以决定要渲染什么来代替它

<div>
{this.props.items.reduce((total,item) => item.quantity + total, 0)}
</div>

reduce 方法所做的是从元素列表中返回单个值。第二个参数是你的初始值,而他的第一个参数是每次迭代都会执行的回调

【讨论】:

    猜你喜欢
    • 2019-01-31
    • 2019-12-12
    • 2017-12-26
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多