【问题标题】:How do I get the TOTAL price from the updated state? (reactjs)我如何从更新的状态中获得总价格? (反应)
【发布时间】: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

标签: reactjs state store price


【解决方案1】:

您可以使用setState 的函数形式来简化您的方法:

 handleQuantityChange = id => {
   const product = products.find(product => product.id === id)

   this.setState(state => ({
     selectedProducts: [...state.selectedProducts, id],
     totalPrice: state.totalPrice + product.price,
   }));
 };

【讨论】:

  • 我试过了,它返回:TypeError: Cannot read property 'price' of undefined, const carsSelected = this.state.selectedProducts; const product = products.find(product => product.id === id) const priceAddition = product.price const oldTotal = this.state.totalPrice const newPrice = priceAddition + oldTotal this.setState({ selectedProducts: [...carsSelected , id], totalPrice: newPrice });
【解决方案2】:

因为 find 方法确实将匹配的记录作为数组对象返回。 所以你已经用这些行替换了你的 find 方法行

const product = products.find(product => product.id === id)
const {price=0}=product[0] && product[0] || {};

【讨论】:

  • 感谢您的帮助,但我在实施您的答案时遇到了麻烦,您能告诉我您的意思吗? (我是新手)
【解决方案3】:

我解决了这个问题,我所要做的就是:

 handleQuantityChange = id => {
    const carsSelected = this.state.selectedProducts
    const oldTotal = this.state.totalPrice
    const newPrice = id.price + oldTotal
    this.setState({
      selectedProducts: [...carsSelected, id],
      totalPrice: newPrice
    });
  };

感谢大家的帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2017-11-08
    • 2019-12-10
    • 2020-10-05
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多