使用......传播,但redux仍然会对状态突变发出警告

时间:2016-06-14 18:20:01

标签: javascript reactjs redux react-redux

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
  });

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

2 个答案:

答案 0 :(得分:11)

[...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});

答案 1 :(得分:0)

好的,我明白了。传播一个对象数组会产生一个新数组,但会链接到相同的对象。为了避免这种变异,我添加了这一行:          的 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
  });