Redux - 如何在 reducer 中向数组添加条目
Redux - How to add entry to array in reducer
我坚持这一点,但无法取得进展 - 我想解决方案很简单,但我想不通。我正在尝试在 reducer 中添加条目,以便 in 中的数据看起来像这样:
state = {
entryId: {
entryName: ["something", "something2", "something3" /* and so on... */]
}
};
到目前为止,这是我得到的最接近的,但是,它没有添加新的唯一条目,而是替换了已经存储的条目。我还需要能够将此项添加到 entryId、entryName 尚不存在的空状态以避免错误:
switch(type) {
case ADD_ENTRY:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: {
[uniqueEntry]: true
}
}
};
}
知道我做错了什么吗?
如果您尝试将元素添加到 entryName
数组的末尾,您应该这样做:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: [
...state[entryId][entryName],
uniqueEntry
]
}
};
ES6 用数组传播是这样的:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const eight = 8;
const newArray = ['stuff', ...array1, 'things', ...array2, ...[7, eight], 9];
console.log(newArray); // ["stuff", 1, 2, 3, "things", 4, 5, 6, 7, 8, 9]
查看 this gist,其中有一个与您正在做的事情非常相似的示例。
我发现这组示例也非常有用。这里有很多很棒的东西:
https://github.com/sebmarkbage/ecmascript-rest-spread
更新:
如果 entryName
像您在评论中所说的那样初始化为 undefined
,您可以这样做:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: [
...state[entryId][entryName] || [],
uniqueEntry
]
}
};
我认为这是一个很好的例子,说明使用 React/redux 使用高度嵌套的数据结构是多么痛苦。 FWIW,有人多次建议我尽可能地压平你的状态。
我坚持这一点,但无法取得进展 - 我想解决方案很简单,但我想不通。我正在尝试在 reducer 中添加条目,以便 in 中的数据看起来像这样:
state = {
entryId: {
entryName: ["something", "something2", "something3" /* and so on... */]
}
};
到目前为止,这是我得到的最接近的,但是,它没有添加新的唯一条目,而是替换了已经存储的条目。我还需要能够将此项添加到 entryId、entryName 尚不存在的空状态以避免错误:
switch(type) {
case ADD_ENTRY:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: {
[uniqueEntry]: true
}
}
};
}
知道我做错了什么吗?
如果您尝试将元素添加到 entryName
数组的末尾,您应该这样做:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: [
...state[entryId][entryName],
uniqueEntry
]
}
};
ES6 用数组传播是这样的:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const eight = 8;
const newArray = ['stuff', ...array1, 'things', ...array2, ...[7, eight], 9];
console.log(newArray); // ["stuff", 1, 2, 3, "things", 4, 5, 6, 7, 8, 9]
查看 this gist,其中有一个与您正在做的事情非常相似的示例。
我发现这组示例也非常有用。这里有很多很棒的东西:
https://github.com/sebmarkbage/ecmascript-rest-spread
更新:
如果 entryName
像您在评论中所说的那样初始化为 undefined
,您可以这样做:
return {
...state,
[entryId]: {
...state[entryId],
[entryName]: [
...state[entryId][entryName] || [],
uniqueEntry
]
}
};
我认为这是一个很好的例子,说明使用 React/redux 使用高度嵌套的数据结构是多么痛苦。 FWIW,有人多次建议我尽可能地压平你的状态。