我想使用传播运算符将数据添加到我的数组中。当其为对象时有效
${TAG}
但是当它是一个数组时
{
...state,
selections: {
...state.selections,
[action.data.type]: action.data
}
我在想
{
...state,
selections: {
...state.selections,
[action.data.type]: [] // Every time i save something it should end up here
}
但是它不起作用,因为... state.selections [action.data.type]其不可迭代的实例。
这就是我要完成的
{
...state,
selections: {
...state.selections,
[action.data.type]: [
...state.selections[action.data.type],
action.data]
}
我试图研究https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
答案 0 :(得分:0)
您可以使用spread
运算符。我非常确定问题是,您尝试添加action.type
,在您的小示例中,该列表将是具有不可迭代类型state.selections
的{{1}}。
object
答案 1 :(得分:0)
尝试一下:
{
...state,
selections: {
...state.selections,
[action.data.type]: Array.isArray(state.selections[action.data.type])
&& [
...state.selections[action.data.type],
action.data]
|| [
state.selections[action.data.type],
action.data]
}
答案 2 :(得分:0)
如果state.selections[action.data.type]
的初始值为[]
,则它应为数组。
如果显示payload
和initialState
的示例,将会容易得多。
action.data
始终是对象吗?
{
...state,
selections: {
...state.selections,
[action.data.type]: Array.isArray(state.selections[action.data.type])
? [...state.selections[action.data.type], action.data]
: action.data
}