【问题标题】:how to add items properly to the state (empty array) in reactjs?如何将项目正确添加到reactjs中的状态(空数组)?
【发布时间】:2019-12-30 14:30:25
【问题描述】:

我试图将项目添加到空数组 selectedProducts,但我添加的每个项目都嵌套在另一个项目中,我的目标是让一个数组包含所有选定的项目分布在里面。 我是新手,所以我们将不胜感激:)

我的状态:

state = {
    products: products,
    selectedProducts: [],
    totalPrice: 0
  };

方法:

handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = Object.assign([{...selectedProducts}],item)
    this.setState(
      {selectedProducts:carsSelected}
    );

结果(每个 0 代表一个嵌套数组,显示一个项目(汽车)):

[{…}, id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …]
0:
0:
0:
__proto__: Object
count: 0
description: "High Performance"
id: 4
img: 
name: "BMW"
price: 120000
total: 0
__proto__: Object
count: 0
description: "Kinda Fast"
id: 3
img: 
name: "Maserati"
price: 800000
total: 0
__proto__: Object
count: 0
description: "Extremely Fast"
id: 2
img: 
name: "Bugatti"
price: 3200000
total: 0
length: 1

【问题讨论】:

  • 嗨大卫,检查我的解决方案,如果有帮助,请告诉我。
  • 谢谢!!!!我不敢相信它是多么简单:)

标签: javascript reactjs state store


【解决方案1】:
handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = [...selectedProducts,item]
    this.setState(
      {selectedProducts:carsSelected}
    );

【讨论】:

    【解决方案2】:

    你可以这样做,

    this.setState({
       selectedProducts: [...this.state.selectedProducts , item]
    });
    

    【讨论】:

      【解决方案3】:

      您不需要同时使用 object.assign 和 spread 运算符。

      数组可以这样使用

      this.setState({
         selectedProducts: [...this.state.selectedProducts , item]
      });
      

      对于object你可以这样使用

      this.setState({
         selectedProducts: {...this.state.selectedProducts , item: '123'}
      });
      

      【讨论】:

        猜你喜欢
        • 2023-01-14
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 2019-02-23
        • 2021-02-19
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多