How to update single value inside specific array item in redux

前端 未结 8 1390
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 01:55

I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page.

8条回答
  •  [愿得一人]
    2020-11-28 02:25

    Very late to the party but here is a generic solution that works with every index value.

    1. You create and spread new array from the old array up to the index you want to change.

    2. Add the data you want.

    3. Create and spread new array from the index you wanted to change to the end of the array

    let index=1;// probabbly action.payload.id
    case 'SOME_ACTION':
       return { 
           ...state, 
           contents: [
              ...state.contents.slice(0,index),
              {title: "some other title", text: "some other text"},
             ...state.contents.slice(index+1)
             ]
        }
    

    Update:

    I have made a small module to simplify the code, so you just need to call a function:

    case 'SOME_ACTION':
       return {
           ...state,
           contents: insertIntoArray(state.contents,index, {title: "some title", text: "some text"})
        }
    

    For more examples, take a look at the repository

    function signature:

    insertIntoArray(originalArray,insertionIndex,newData)
    

提交回复
热议问题