2016-06-14 28 views
2

終極版略知調度警告:使用...蔓延,但仍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 
    }); 

又怎麼了如果我使用[...傳播],改變狀態?

回答

8

這裏的[...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}); 
+0

非常好!恰恰是我幾分鐘前才意識到的,但更加優雅的方式。 – Syberic

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