using …spread, but redux still throws warning about state mutation

前端 未结 2 1331
北荒
北荒 2021-01-03 05:46

Redux throws Warning on dispatch:

Error: A state mutation was detected inside a dispatch, in the path: 
roundHistory.2.tickets. Take a look at the reducer(s)         


        
相关标签:
2条回答
  • 2021-01-03 06:14

    The [...state.roundHistory] here is similar to [].concat(state.roundHistory). It's creating a new array, but the objects in the array are shared with state.roundHistory. If you want to mutate them you'll need to make copies of each item.

    You can do this using Object.assign, similar to how what you did for your return value:

    var archive = state.roundHistory.map(value => Object.assign({}, value));
    

    Or (as you suggested in your own answer), you can use object-spread notation:

    var archive = state.roundHistory.map(value => {...value});
    
    0 讨论(0)
  • 2021-01-03 06:27

    Okay i got it. Spreading an array of objects gives a new array but with links to same objects. To avoid the mutation, i added this line: archive[i] = {...state.roundHistory[i]};

    case 'ARCHIVE_TICKETS' :
      var archive = [...state.roundHistory];
      for (var i in archive) {
        archive[i] = {...state.roundHistory[i]};
        if (archive[i]._id === action.roundId) {
          archive[i].tickets = action.data;
        }
      }
      return Object.assign({}, state, {
        roundHistory: archive
      });
    
    0 讨论(0)
提交回复
热议问题