简体   繁体   English

setState 未正确更新 state

[英]setState is not correctly updating state

I'm writing a function that adds sub varieties to an array of varieties ie each variety is an object having a property called varieties which is an array of objects also.我正在编写一个 function ,它将子品种添加到品种数组中,即每个品种都是一个 object 具有一个称为品种的属性,它也是一个对象数组。

the initial varieties state is初始品种 state 是

const defaultInitVarieties = [];

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

addInner is declared as: 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);
};

PROBLEM问题

bearing in mind that varieties has one object in the array, the results of console.log('copy after', copy);请记住,品种在数组中有一个 object,console.log('copy after', copy); 的结果is;是;

[{
   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"
    }
   ]
  }]

which is what I expect.这是我所期望的。

However , when I setVariety with that what I get is但是,当我使用它设置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: []
}]

ie the newEntry addition is added as another variety instead of it being a subvariety!即 newEntry 添加是作为另一个品种添加的,而不是作为一个子品种!

Try setVarieties(newParent);尝试setVarieties(newParent); instead of setVarieties(copy);而不是setVarieties(copy); . . If you want to see the expected change in console then change copy[index] = newParent;如果您想在控制台中查看预期的更改,请更改copy[index] = newParent; to copy = newParent; copy = newParent; with this you won't need to change setVarieties(copy);有了这个你就不需要改变setVarieties(copy); statement.陈述。

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

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