setState未正确更新状态

时间:2020-04-14 18:03:13

标签: javascript reactjs

我正在编写一个函数,该函数将子变体添加到变体数组中,即每个变体是一个对象,该对象具有称为变体的属性,这也是对象的阵列。

初始变种状态为

const defaultInitVarieties = [];

const [varieties, setVarieties] = useState(defaultInitVarieties);

addInner声明为:

const addInner = (newEntry, parentId) => {
console.log('running add inner');
//copy varieties
let copy = [...varieties];
// get parent via id
let parent = copy.find(each => each.id === parentId);
// get index of parent
const index = copy.findIndex(each => each.id === parentId);
//create new color variety
const newParent = {
  ...parent,
  varieties: [
    ...parent.varieties,
    {
      index: parent.varieties.length < 1 ? 0 : parent.varieties.length,
      edit: false,
      ...newEntry,
    }
  ]
};
//mutate copy
console.log('copy before', copy)
copy[index] = newParent;
console.log('copy after', copy);
//update state
setVarieties(copy);
};

问题

请记住,品种在数组中有一个对象,即console.log('copy after',copy);的结果;是;

[{
   id: "31943632-0f91-419c-b6ee-55a3d92fdd28"
   imageUrl: "/static/media/choose-image.ba6e31d9.svg"
   size: "24"
   quantity: 1
   price: "2000"
   discountPrice: "2000"
   color: "red"
   varieties: [
    {
      index: 0
      edit: false
      id: "eb351fff-4216-4080-8cc2-31e677aa5b0e"
      imageUrl: "/static/media/choose-image.ba6e31d9.svg"
      size: "22"
      quantity: 1
      price: "2000"
      discountPrice: "2000"
      color: "red"
    }
   ]
  }]

这是我的期望。

但是,当我设置Variety时,我得到的是

[{
  id: "31943632-0f91-419c-b6ee-55a3d92fdd28"
  imageUrl: "/static/media/choose-image.ba6e31d9.svg"
  size: "24"
  quantity: 1
  price: "2000"
  discountPrice: "2000"
  color: "red"
  varieties: []
},
{
  id: "eb351fff-4216-4080-8cc2-31e677aa5b0e"
  imageUrl: "/static/media/choose-image.ba6e31d9.svg"
  size: "22"
  quantity: 1
  price: "2000"
  discountPrice: "2000"
  color: "red"
  varieties: []
}]

即将newEntry添加为另一个变体,而不是它的子变体!

1 个答案:

答案 0 :(得分:0)

尝试使用setVarieties(newParent);而不是setVarieties(copy);。如果要在控制台中看到预期的更改,则可以将copy[index] = newParent;更改为copy = newParent;,而无需更改setVarieties(copy);语句。