繁体   English   中英

setState 未正确更新 state

[英]setState is not correctly updating state

我正在编写一个 function ,它将子品种添加到品种数组中,即每个品种都是一个 object 具有一个称为品种的属性,它也是一个对象数组。

初始品种 state 是

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);
};

问题

请记住,品种在数组中有一个 object,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 添加是作为另一个品种添加的,而不是作为一个子品种!

尝试setVarieties(newParent); 而不是setVarieties(copy); . 如果您想在控制台中查看预期的更改,请更改copy[index] = newParent; copy = newParent; 有了这个你就不需要改变setVarieties(copy); 陈述。

暂无
暂无

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

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