如何将项目正确添加到 reactjs 中的状态(空数组)?

how to add items properly to the state (empty array) in reactjs?

我试图将项目添加到空数组 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
handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = [...selectedProducts,item]
    this.setState(
      {selectedProducts:carsSelected}
    );

你可以简单地这样做,

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

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

对于数组你可以这样使用

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

对于对象你可以这样使用

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