使用 ...spread,但 redux 仍然会发出有关状态突变的警告

IT技术 javascript reactjs redux react-redux
2021-05-17 11:02:10

Redux 在调度时抛出警告:

Error: A state mutation was detected inside a dispatch, in the path: 
roundHistory.2.tickets. Take a look at the reducer(s) handling the action {"type":"ARCHIVE_TICKETS","roundId":"575acd8373e574282ef18717","data":[{"_id":"575acd9573e574282ef18718","value":7,"user_id":"574c72156f355fc723ecdbbf","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575acd9573e574282ef18719","value":9,"user_id":"574c72156f355fc723ecdbbf","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575acd9573e574282ef1871a","value":8,"user_id":"574c72156f355fc723ecdbbf","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575acdac73e574282ef1871b","value":19,"user_id":"574c72156f355fc723ecdbbf","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575ad50c4c17851c12a3ec23","value":29,"user_id":"57522f0b1f08fc4257b9cbc6","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575ad50c4c17851c12a3ec24","value":28,"user_id":"57522f0b1f08fc4257b9cbc6","round_id":"575acd8373e574282ef18717","__v":0},{"_id":"575ad

唯一的减速器处理ARCHIVE_TICKETS动作是这个:

case 'ARCHIVE_TICKETS' :
  var archive = [...state.roundHistory];
  for (var i in archive) {
    if (archive[i]._id === action.roundId) {
      archive[i].tickets = action.data;
    }
  }
  return Object.assign({}, state, {
    roundHistory: archive
  });

如果我使用 [...spread],它如何改变状态?

2个回答

[...state.roundHistory]这里类似[].concat(state.roundHistory)它创建一个新的数组,但对象数组与共享state.roundHistory如果你想改变它们,你需要制作每个项目的副本。

您可以使用 来执行此操作Object.assign,类似于您为返回值所做的操作:

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

或者(正如您在自己的答案中所建议的那样),您可以使用对象扩展表示法返回具有相同对象值的数组:

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

好的,我明白了。传播一个对象数组会给出一个新数组,但带有指向相同对象的链接。为了避免突变,我添加了这一行: 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
  });