Redux - 如何在减速器中向数组添加条目 [英] Redux - How to add entry to array in reducer

查看:20
本文介绍了Redux - 如何在减速器中向数组添加条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持这一点,我无法进步 - 我想解决方案很简单,但我想不通.我正在尝试在减速器中添加条目,因此输入中的数据看起来像这样:

I stuck with this bit and I can't progress - I guess solution is simple but I can't figure out. I'm trying to add entry in reducer so data in in would look something this:

state = {
  entryId: {
    entryName: ["something", "something2", "something3" /* and so on... */]
  }
};

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

So far this is the closest I get, but, instead of adding new unique entry, it is replacing the one that is stored already. Also I need to be able to add this item to empty state where entryId, entryName doesn't exist yet to avoid error:

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

知道我做错了什么吗?

推荐答案

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

If you're trying to add an element to the end of the entryName array you should be doing:

return {
  ...state,
  [entryId]: {
    ...state[entryId],
    [entryName]: [
      ...state[entryId][entryName],
      uniqueEntry
    ]
  }
};

使用数组展开的 ES6 的工作方式如下:

ES6 spread with arrays works like this:

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]

查看这个要点,其中有一个与您正在做的事情非常相似的示例.

Check out this gist which has an example of something very similar to what you're doing.

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

I found this set of examples extremely helpful as well. A lot of great stuff in here:

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

更新:

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

If entryName is initialized to undefined like you say in your comment, you could do this:

return {
  ...state,
  [entryId]: {
    ...state[entryId],
    [entryName]: [
      ...state[entryId][entryName] || [],
      uniqueEntry
    ]
  }
};

我认为这是一个很好的例子,说明使用高度嵌套的数据结构使用 React/redux 是多么痛苦.FWIW,有人多次向我推荐尽可能压平你的状态.

I think this is a pretty great example of how painful it can be working with React/redux using a heavily nested data structure. FWIW, it's been recommended to me many times to flatten your state as much as possible.

这篇关于Redux - 如何在减速器中向数组添加条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆