Replace array item with another one without mutating state

后端 未结 3 840
死守一世寂寞
死守一世寂寞 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:36

    Note that Array.prototype.map() (docs) does not mutate the original array so it provides another option:

     const INITIAL_STATE = {
       contents: [ {}, {}, {}, etc.. ],
       meta: {}
     }
    
     // Assuming this action object design
     {
       type: MY_ACTION,
       data: {
         // new content to replace
       },
       meta: {
         index: /* the array index in state */,
       }
     }
    
     function myReducer(state = INITIAL_STATE, action) {
       switch (action.type) {
         case MY_ACTION: 
           return {
             ...state,
             // optional 2nd arg in callback is the array index
             contents: state.contents.map((content, index) => {
               if (index === action.meta.index) {
                 return action.data
               }
    
               return content
             })
           }
       }
     }
    

提交回复
热议问题