简体   繁体   English

React setState 更新不正确

[英]React setState is incorrectly updating

const [cartItems, setcartItems] = useState([] as Product[]);

const addItemToCart = (product: Product) => {
  setcartItems((preCartItems) => {
    const updatedcart = [...preCartItems];
    if(!updatedcart.length)
      updatedcart.push(product)
    // updatedcart[0].price original value 1
    updatedcart[0].price = updatedcart[0].price + 1 ;
    console.log(updatedcart[0].price); // prints 2
    console.log(updatedcart); // printed object is saying price value 3
    return updatedcart;
  });
};

I am unable to understand how the value is incremented automatically by 1 and why is the value on the object giving a different output compared to the value accessed by the dot operator我无法理解该值如何自动增加 1,以及为什么 object 上的值与点运算符访问的值相比给出不同的 output

The problem is that you're mutating your state within the setcartItems .问题是你在 setcartItems 中改变你的setcartItems

Doing const updatedcart = [...preCartItems];const updatedcart = [...preCartItems]; is not copying the objects in preCartItems , it's just spreading the reference of the same objects in a new array.不是复制preCartItems中的对象,它只是将相同对象的引用传播到一个新数组中。

Then you're mutating the object here updatedcart[0].price = updatedcart[0].price + 1;然后你在这里改变 object updatedcart[0].price = updatedcart[0].price + 1; . .

This will lead to two different versions of the state, hence the inconsistent result.这将导致 state 的两个不同版本,因此结果不一致。

If you want to copy the objects you should do如果你想复制你应该做的对象

const updatedcart = preCartItems.map(item => ({ ...item }));

This returns a new array of new objects and you can do any operation you want on them.这将返回一个新对象的新数组,您可以对它们执行任何操作。 This way of copying an array of objects is also shallow, it only works for 1 depth level, if you want to copy also nested objects you need a more robust function.这种复制对象数组的方式也很浅,它仅适用于 1 个深度级别,如果您还想复制嵌套对象,则需要更健壮的 function。

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

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