简体   繁体   中英

Redux UI wont update when changing state of nested array

I'm fairly new to Redux.

My Web application is an eCommerce website where users have multiple carts (each with an id and name) and can place different items in each cart (inside an items array).

When a user deletes an item from the cart, my console.log() statements show that the carts array is being updated in the store, however the User interface doesn't reflect that unless i insert a new cart object inside of the carts array.

  1. Why can't i update a nested array the same way i update a normal array in the store?

  2. How do i fix this?


My initial Store

const intialStore = {
    carts: [],
    first_name : "ford",
    last_name : "doly"

} 

My Reducer Function


export default function reducer (store = intialStore, action) {
    let {type, payload} = action;
    switch(type) {

     case DELETE_ITEM_IN_A_CART : {
    
                let carts = [...store.carts]
    
    
  let newCarts =   carts.map((cartItem, index) => {
    
                    if (index == payload.cartIndex){
    
                        let array = [...cartItem.items]
                        array.splice(payload.itemIndex, 1) 
    
                        cartItem.items = [...array  ]
                    }
    
                    
                    
    
                    return cartItem ;
                })
    
            
                console.log(carts)
    
                //carts[payload.cartIndex].items.splice(payload.itemIndex, 1)
    
               
               
                return {...store, carts : newCarts}
            }

       default:
          return {...store}
}

My Action Creator

export const deleteitemInCart = (cartIndex, itemIndex) => {
    return {
        type: DELETE_ITEM_IN_A_CART,
        payload: {
            cartIndex,
            itemIndex
        }
    }
}

map returns a new array, it does not mutate the original (which is good, we don't want to mutate it). But this means in order for your mapping actions to be persisted, you need to assign the result to a variable.


let newCarts = carts.map(...)

...

return {...store, carts: newCarts}

Right now, you're just returning the same carts array as the new state.

When you use the spread operator, you're only making a shallow copy. In your reducer, try using JSON.parse(JSON.stringify(carts)) in order to make a deep copy before performing the splice operation. This would ensure you are not mutating any existing state, but operating on a copy and returning a new copy at the end of the reducer.

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