[英]How to add a callback function to the .map method
I want my function to calculate the total cost of my shopping cart and then set the state of my component to those totals, but I need the calculation done first and then the state set after the calculations are complete. 我希望函数计算购物车的总成本,然后将组件的状态设置为这些总计,但是我需要先完成计算,然后在计算完成后再设置状态。 When I run the code below, the state never gets set.
当我运行下面的代码时,状态永远不会被设置。
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>
);
}
});
two points: 两点:
In pseudo code, the structure of your component should look more like: 在伪代码中,组件的结构应类似于:
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>
);
}
}
Map is synchronous . 地图是同步的。 Why you need setState, use variable enough.
为什么需要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>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.