简体   繁体   中英

react state mutation issue

Im doing a cart on React but i have this lines on a reducer function:

state.cartItems.push({
      ...action.payload,
      quantity: 1,
    });

previous lines causes undesired behaviors.

my understanding its that must'n do a mutations on the state, so i try this instead:

state.cartItems.concat({
      ...action.payload,
      quantity: 1,
    });

and not working

I got the idea from Learning React 2 by Alex Banks and Eve Porcello, the show this example:

let list = [{ title: "Rad Red" }, { title: "Lawn" }, { title: "Party Pink" }];

const addColor = (title, array) => array.concat({ title });

console.log(addColor("Glam Green", list).length); // 4
console.log(list.length); // 3”

Though that this would work but don't do anything

For more live version of the app its here

and for the specific file go here

Im doing a cart on React but i have this lines on a reducer function:

state.cartItems.push({
      ...action.payload,
      quantity: 1,
    });

previous lines causes undesired behaviors.

my understanding its that must'n do a mutations on the state, so i try this instead:

state.cartItems.concat({
      ...action.payload,
      quantity: 1,
    });

and not working

I got the idea from Learning React 2 by Alex Banks and Eve Porcello, the show this example:

let list = [{ title: "Rad Red" }, { title: "Lawn" }, { title: "Party Pink" }];

const addColor = (title, array) => array.concat({ title });

console.log(addColor("Glam Green", list).length); // 4
console.log(list.length); // 3”

Though that this would work but don't do anything

For more live version of the app its here

and for the specific file go here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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