使用......传播,但redux仍然会对状态突变发出警告 [英] using ...spread, but redux still throws warning about state mutation

查看:138
本文介绍了使用......传播,但redux仍然会对状态突变发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Redux在调度时抛出警告:

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) 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 actio n是这一个:

The only reducer handling ARCHIVE_TICKETS action is this one:

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

How can it mutate the state if i use [...spread]?

推荐答案

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

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.

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

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

这篇关于使用......传播,但redux仍然会对状态突变发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆