如何将回调函数添加到 .map 方法
How to add a callback function to the .map method
我希望我的函数计算购物车的总成本,然后将组件的状态设置为这些总计,但我需要先完成计算,然后在计算完成后设置状态。当我运行下面的代码时,状态永远不会被设置。
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
}, () => {
this.setState({
subtotal: newSubtotal,
total: newTotal
});
});
return (
<div>
<ul>
<li>Subtotal: ${this.state.subtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${this.state.total}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
在伪代码中,组件的结构应该更像:
MyCartTotalComponent => {
// no need for state: if your props contain cart, then every time cart changes
// your component gets new props, calculates total, and renders
render() {
// calculate stuff and store in local cart variable
var cart = {};
cart.total = this.props.cart.reduce(
function(prev,curr){
return prev + curr.price;
},0);
// render stuff
return (
<div>
...
<li>{cart.Total}</li>
...
</div>
);
}
}
两点:
- 您应该使用 .reduce 函数来计算总和。
- 你不应该在你的render()中使用this.setState,我建议使用ComponentDidMount或InitialState 。
映射是同步的。为什么需要 setState,使用变量足够多。
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
});
return (
<div>
<ul>
<li>Subtotal: ${newSubtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${newTotal}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
相关文章:
- 使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
- 在 Array.map() 中调用类方法
- 如何将回调函数添加到 .map 方法
- 下划线.js .map 方法会中断 IE8
- 使用map方法将javascript对象数组转换为其他对象数组
- 在 mongo map 中调用外部 javascript 函数(对象)或减少上下文的可能方法
- 使用类似于 Array.prototype.map() 的方法将数组转换为键值对象
- 获取对象 #
- 如何使用jquery、json和自定义数据属性将map方法嵌套在map方法中
- 在map方法中获取数组键
- ES6中的map方法和lodash的区别是什么?
- 从Map方法中有条件返回对象
- javascript开发人员在什么情况下使用map()方法?
- 为什么Map没有Map方法?
- 在javascript的.map()方法中使用迭代器和if语句
- rails上的ruby-json上的.map方法,使用Javascript中的parent和wthout
- Map方法更改旧数组
- 在下划线/lodash中,如何避免在“map”方法中重复计算
- 在map()方法中更改对象数组中每个属性的值
- 凯撒密码在Javascript中使用shiftChar()函数和Array.map()方法