Redux - 如何在reducer中向数组添加条目

elo*_*eon 19 ecmascript-6 reactjs ecmascript-7 redux react-redux

我坚持这一点,我无法进步 - 我想解决方案很简单,但我无法弄清楚.我正在尝试在reducer中添加条目,因此in in中的数据看起来像这样:

state = {
  entryId: {
    entryName: ["something", "something2", "something3" /* and so on... */]
  }
};
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我得到的最接近的,但是,它不是添加新的唯一条目,而是替换已经存储的条目.此外,我需要能够将此项添加到空状态,其中entryId,entryName尚不存在以避免错误:

switch(type) {
  case ADD_ENTRY:
    return {
      ...state,
      [entryId]: {
        ...state[entryId],
        [entryName]: {
          [uniqueEntry]: true
        }
      }
    };
}
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?

jay*_*bee 22

如果您尝试将元素添加到entryName数组的末尾,那么您应该这样做:

return {
  ...state,
  [entryId]: {
    ...state[entryId],
    [entryName]: [
      ...state[entryId][entryName],
      uniqueEntry
    ]
  }
};
Run Code Online (Sandbox Code Playgroud)

使用数组传播的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]
Run Code Online (Sandbox Code Playgroud)

看看这个要点,其中有一个非常类似于你正在做的事情的例子.

我发现这组例子也非常有用.这里有很多很棒的东西:

https://github.com/sebmarkbage/ecmascript-rest-spread

更新:

如果entryName初始化为undefined您在评论中说的那样,您可以这样做:

return {
  ...state,
  [entryId]: {
    ...state[entryId],
    [entryName]: [
      ...state[entryId][entryName] || [],
      uniqueEntry
    ]
  }
};
Run Code Online (Sandbox Code Playgroud)

我认为这是一个很好的例子,说明使用重度嵌套的数据结构使用React/redux会有多痛苦.FWIW,我多次建议尽可能地平整你的状态.