简体   繁体   English

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

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

im trying to add items to the empty array selectedProducts, but every item i add becomes nested inside the other, my goal is to have one array with all the items selected spread inside. 我试图将项目添加到空数组selectedProducts中,但是我添加的每个项目都嵌套在另一个内部,我的目标是要使一个数组与所有选定的项目一起传播到内部。 im new to react so examples would be greatly appreciated :) 我是新来的人,所以示例将不胜感激:)

my state: 我的状态:

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

the method: 方法:

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

the result (every 0 represent a nested array that shows one item(car)): 结果(每个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

You can simply do this, 您可以简单地做到这一点,

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

you don't need to use object.assign and spread operator together. 您不需要一起使用object.assign和spread运算符。

for array you can use like this 对于数组,您可以像这样使用

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

for object you can use like this 对于对象,您可以像这样使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM