簡體   English   中英

使用 ...spread,但 redux 仍然會發出有關狀態突變的警告

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

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],它如何改變狀態?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM