Replace array item with another one without mutating state

后端 未结 3 853
死守一世寂寞
死守一世寂寞 2021-01-01 18:52

This is how example of my state looks:

const INITIAL_STATE = {
 contents: [ {}, {}, {}, etc.. ],
 meta: {}
}

I need to be able and somehow

3条回答
  •  独厮守ぢ
    2021-01-01 19:45

    Just to build on @sapy's answer which is the correct one. I wanted to show you another example of how to change a property of an object inside an array in Redux without mutating the state.

    I had an array of orders in my state. Each order is an object containing many properties and values. I however, only wanted to change the note property. So some thing like this

    let orders = [order1_Obj, order2_obj, order3_obj, order4_obj];
    

    where for example order3_obj = {note: '', total: 50.50, items: 4, deliverDate: '07/26/2016'};

    So in my Reducer, I had the following code:

    return Object.assign({}, state,
    {
      orders: 
        state.orders.slice(0, action.index)
        .concat([{
          ...state.orders[action.index],
          notes: action.notes 
        }])
        .concat(state.orders.slice(action.index + 1))
       })
    

    So essentially, you're doing the following:

    1) Slice out the array before order3_obj so [order1_Obj, order2_obj]

    2) Concat (i.e add in) the edited order3_obj by using the three dot ... spread operator and the particular property you want to change (i.e note)

    3) Concat in the rest of the orders array using .concat and .slice at the end .concat(state.orders.slice(action.index + 1)) which is everything after order3_obj (in this case order4_obj is the only one left).

提交回复
热议问题