【问题标题】:using ...spread, but redux still throws warning about state mutation使用 ...spread,但 redux 仍然会引发有关状态突变的警告
【发布时间】:2016-06-14 18:20:01
【问题描述】:

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动作的reducer是这个:

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],它如何改变状态?

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 太棒了!正是我几分钟前意识到的,但以更优雅的方式。
    • 嗨,我试过这个 export default (state, action) => { return Object.assign({}, { ...state, messages: state.messages.map(value => Object. assign({}, value)).concat(action.payload) }) } 还是有错误请查看stackoverflow.com/questions/58120646/…
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2014-02-13
      • 1970-01-01
      • 2017-09-26
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      相关资源
      最近更新 更多