本文介绍了在不改变状态的情况下用另一个替换数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的状态示例:
const INITIAL_STATE = {
contents: [ {}, {}, {}, etc.. ],
meta: {}
}
我需要能够并以某种方式替换内容数组中知道其索引的项目,我已经尝试过:
I need to be able and somehow replace an item inside contents array knowing its index, I have tried:
return {
...state,
contents: [
...state.contents[action.meta.index],
{
content_type: 7,
content_body: {
album_artwork_url: action.payload.data.album.images[1].url,
preview_url: action.payload.data.preview_url,
title: action.payload.data.name,
subtitle: action.payload.data.artists[0].name,
spotify_link: action.payload.data.external_urls.spotify
}
}
]
}
其中 action.meta.index
是我想用另一个内容对象替换的数组项的索引,但我相信这只是将整个数组替换为我正在传递的这个对象.我也想过使用 .splice()
但这只会改变数组?
where action.meta.index
is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice()
but that would just mutate the array?
推荐答案
Splice
改变你需要使用的数组 Slice
.并且您还需要 concat
切片.
Splice
mutate the array you need to use Slice
. And you also need to concat
the sliced piece .
return Object.assign({}, state, {
contents:
state.contents.slice(0,action.meta.index)
.concat([{
content_type: 7,
content_body: {
album_artwork_url: action.payload.data.album.images[1].url,
preview_url: action.payload.data.preview_url,
title: action.payload.data.name,
subtitle: action.payload.data.artists[0].name,
spotify_link: action.payload.data.external_urls.spotify
}
}])
.concat(state.contents.slice(action.meta.index + 1))
}
这篇关于在不改变状态的情况下用另一个替换数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!