【发布时间】:2020-01-01 00:25:49
【问题描述】:
我需要在添加项目时动态更新总数
selectedProducts 是 onClick 与所选项目更新的数组,项目包括价格(在对象中:'price'),我需要获取总项目的价格,并相应地更新 totalPrice。
* 如果可能,我会尝试将所有内容都保存在一个函数中 *
class App extends Component {
state = {
products: products,
selectedProducts: [],
totalPrice: 0,
};
handleQuantityChange = id => {
const carsSelected = this.state.selectedProducts;
const price = products.map(id => id.price).find((id)=> {
return id
} )
const priceAddition = price
const oldPrice = this.state.totalPrice;
const newPrice = oldPrice + priceAddition;
this.setState({
selectedProducts: [...carsSelected, id],
totalPrice:newPrice,
});
};
【问题讨论】:
-
这里的问题是什么?你似乎有一个解决方案,什么不起作用?
-
我不断收到 TypeError: Cannot read property 'price' of undefined