简体   繁体   中英

How to mutate state in react?

I'm trying the change the value of an object field that is nested in an array. I keep getting this error, "Cannot assign to read only property '0' of object '[object Array]'"

Here is what the state looks like

{
    "school stuffs": [
        {
            "_id": "629332e33f0e48af3d626645",
            "completed": false,
            
        },
        {
            "_id": "629425fc9c50b142dff947a9",
            "completed": true,
            
        }
    ],
    "household and furniture": [
        {
            "_id": "629334424709234a344c0189",
            "completed": false,
            
        },
        {
            "_id": "629334f12da7859af0828c9a",
            "completed": false,
            
        }
    ]
}

Here is the code I'm using to mutate the state and change the value of "completed" to the opposite value of the current Boolean.

const newArray = { ...productArray,  [value]: {...productArray}[value]  }
const index = productArray[value].findIndex(index => index._id === innerElement._id)
newArray[value][index].completed = !newArray[value][index].completed
console.log(newArray[value][index].completed); 

The thing with react is that, you should not mutate the state, for that purpose exist useState, and pure functions methods, like in the next example: Imagine you have a shopping cart.

const [cart, setCart] = useState([]);

And you want to add a product, you could do it this way:

const addCart = product => {
  setCart([...cart, product]) // Using spread syntax.
  setCart(cart.concat(product)) // Using pure functions.
}

If you want to mutate a prop in an object inside a state, this is the way you could do it:

const increaseQuantity = id => {
  const mappedCart = cart.map(prd => prd.id === id ? {...prd, quantity: prd.quantity + 1} : prd);
  setCart(mappedCart)
}

Of course you can use simple for loops, or other ways, but the matter here is that you can't mutate the state in react.

I hope i have been able to help you

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