简体   繁体   English

如何将列表项作为键添加到 redux 中的 object?

[英]How to add items of list as keys to an object in redux?

I am using Redux with Reactjs .我正在使用ReduxReactjs

According to Redux Documentation :根据Redux 文档

return new state objects, instead of mutating the previous state.返回新的 state 对象,而不是改变以前的 state。

I have an object with its present state as:我有一个 object 及其当前的 state 为:

state = [..., {id: 6, details: []}, ..., ...]

and I have an array of keys (all strings and unique) like this:我有一个键数组(所有字符串和唯一的),如下所示:

list: ["A", "B", "C"]

In javascript , if I do like this:javascript中,如果我这样做:

for (const key of list) {
  exampleDetails[key] = null
} 

I get my desired output:我得到了我想要的 output:

exampleDetails // ["A": null, "B": null, "C": null]
exampleDetails["A"] // null <= what I actually need

But, how to get this next state the redux way, that is, without mutation?但是,如何得到下一个 state 的 redux 方式,即没有突变?

switch(state = [], action) {
  case 'MY_ACTION':
    return state.map(obj => {
      if (obj.id === action.id) {
        return {
          id: obj.id,
          details: [
            ...obj.details,
            /* what to do here? where list is => action.list */
          ]
        }
      } else return obj
    })
  default:
    return state
}

EDIT编辑

I didn't mean to say that I was writing something this in the code:我并不是说我在代码中写了这样的东西:

["A": null, "B": null, "C": null]

This is what I am getting as an output in the browser console:这就是我在浏览器控制台中得到的 output :

在此处输入图像描述

EDIT编辑

switch(state = [], action) {
  case 'MY_ACTION':
    return state.map(obj => 
      (obj.id === action.id ? {...obj, details: action.list.reduce((acc, element) => { acc[element] = null; return acc; }, {}) } : obj)
    )
  default:
    return state
}

I think you are mixing up the concept between array and object.我认为您混淆了数组和 object 之间的概念。 What you are trying to achieve is an object with the list element as the key.您想要实现的是一个 object ,其中列表元素作为键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM