Redux在不改变状态的情况下推送到嵌套数组 [英] Redux pushing to a nested array without mutating the state
问题描述
我有一个看起来像这样的状态对象:
I have a state object that looks like this:
PlaylistDictionary: {
someId: {
pages: [] // trying to push something to this array here
},
someId2: {
pages: [] // trying to push something to this array here
}, etc
}
我正在尝试更新"pages"数组,但是我不断收到一条错误消息,说我正在改变状态..我不明白,因为如果我用Object复制状态对象.分配...我如何改变状态?谢谢你的帮助
I'm trying to update the "pages" array but I keep getting an error saying I'm mutating the state.. which I don't understand because if I'm making a copy of the state object with Object.assign... how am i mutating the state? thank you for any help
case types.ADD_PAGE_TO_PLAYLIST: {
let playlistDictCopy = Object.assign({}, state.playlistDict );
if ( !playlistDictCopy[ action.playlistId ].hasOwnProperty('pages') ) {
playlistDictCopy[ action.playlistId ].pages = [];
}
playlistDictCopy[ action.playlistId ].pages.push( action.pageId );
return Object.assign( {}, state, { playlistDict: playlistDictCopy } );
}
推荐答案
您正在制作状态对象的浅表副本,根本不复制任何属性值,包括数组本身,因此您正在进行变异数组.
You're making a shallow copy of the state object, you are not copying any of the property values at all, including the array itself, so you are mutating the array.
您的.push
调用将更改数组,并且由于尚未创建新数组,因此也会影响所有以前存储的状态对象.
Your .push
call changes the array, and since you haven't created a new array, that will affect all previously stored state objects as well.
你可以做
playlistDictCopy[ action.playlistId ].pages = playlistDictCopy[ action.playlistId ].pages.concat([action.pageId]);
或
playlistDictCopy[ action.playlistId ].pages = [ ...playlistDictCopy[ action.playlistId ].pages, action.pageId]);
而是创建一个新数组.
这篇关于Redux在不改变状态的情况下推送到嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!