Reducer – 添加新元素

huangapple go评论82阅读模式
英文:

Reducer - add new element

问题

Here's the translated code with the problematic parts:

我有这个存储

const initialActors = {
    list: '演员名单',
    actors: [
        {
            name: '安吉丽娜·朱莉',
            involved: true
        },
        {
            name: '布拉德·皮特',
            involved: false
        },
    ]
}

我有一个用于向存储添加新演员的减速器

const actors = (state = initialActors, action) => {
    switch(action.type){
        case 'ADD_NEW':
            return {
                ...state,
                actors: [
                    ...state.actors,
                    {
                        name: action.name,
                        involved: action.involved
                    }
                ]
            }
        default:
            return state
    }
}

我也有一个操作创建器但它并不重要我分派它并显示我的状态

store.dispatch(addNew({name: "你好", involved: true}) ); // 我有这个操作创建器
console.log(store.getState())

Please note that I've made corrections to your code to fix the issues you mentioned.

英文:

I have this store:

const initialActors = {
    list: 'Actor\'s lists',
    actors: [
        {
            name: 'Angelina Jole',
            involved: true
        },
        {
            name: 'Bratt Pitt',
            involved: false
        },
    ]
}

I have a reducer to add a new actor to my store:

const actors = (state = initialActors, action) => {
    switch(action.type){
        case 'ADD_NEW':
            return {
                ...state.list,
                actors: [
                    ...state.actors,
                    action.name,
                    action.involved
                ]
            }
        default:
            return state
    }
}

I have a action creator too but it doesn't important. I dispatch that and display my state:

store.dispatch(addNew({name: "Hello", involved: true}) ); // I have this action creator
console.log(store.getState()

console.log displays very difficult object with letters like: {0: "A", 1: "c"}. What is wrong?

@Edit
I tryed change ...state.list to state list like this:

const actors = (state = initialActors, action) => {
    switch(action.type){
        case 'ADD_NEW':
            return {
                state.list,
                actors: [
                    ...state.actors,
                    action.name,
                    action.involved
                ]
            }

        
        default:
            return state
    }
}

but I have this error:

> Parsing error: Unexpected token, expected ","
Similiar situation I have if I tryed modify actors array:

case 'ADD_NEW':
    return {
        ...state.list,
        actors: [
            ...state.actors,
            {
                action.name,
                action.involved
            }
            
        ]
    }

Error message is this same but point at action object (action.name).

答案1

得分: 1

在你的 reducer 中,你错误地展开了 state.list。因为它是一个字符串,所以你得到了所有的字母。你应该在那里展开 state。因为你想要保留你的 state,除了 actors 数组。这就是为什么你要展开整个 state 并保留 list(如果还有其他内容的话)。

另外,你添加项目的方式有问题,它应该是一个对象。

const actors = (state = initialActors, action) => {
  const { name, involved } = action;

  switch (action.type) {
    case "ADD_NEW":
      return {
        ...state,
        actors: [
          ...state.actors,
          {
            name,
            involved
          }
        ]
      };
    default:
      return state;
  }
};
英文:

In your reducer, you are mistakenly spreading state.list. Since it is a string, you are getting all the letters. You should spread the state there. Because, you want to keep your state, other than actors array. This is why you spread the whole state and keep the list (with others if there would be).

Also, you are adding your item wrong, it should be an object.

const actors = (state = initialActors, action) => {
  const { name, involved } = action;

  switch (action.type) {
    case "ADD_NEW":
      return {
        ...state,
        actors: [
          ...state.actors,
          {
            name,
            involved
          }
        ]
      };
    default:
      return state;
  }
};

答案2

得分: 0

你只是犯了一个小错误,你需要将其添加为一个带有2个属性的对象,就像 [...state.actors, { action.name, action.involved }],而不是你之前所做的。

来自Spread syntax的文档:

Spread语法允许可迭代的对象(例如数组表达式或字符串)在期望零个或多个参数(用于函数调用)或元素(用于数组字面量)的位置扩展,或者在期望零个或多个键值对(用于对象字面量)的位置扩展对象表达式。

像这样:

const actors = (state = initialActors, action) => {
    switch(action.type){
        case 'ADD_NEW':
            return {
                ...state,
                actors: [
                    ...state.actors,
                    {  
                       name: action.name,
                       involved: action.involved
                    }
                ]
            }
        default:
            return state
    }
}

考虑以下示例:

var array = [
  {  
    name: 'someone',
    involved: false,
  }
];

console.log([...array, { name: 'hello', involved: true }]);

希望这可以帮助你!

英文:

Just a small mistake what you did, you need to add as an object with 2 properties like [...state.actors, { action.name, action.involved }] instead of what you did.

From Spread syntax's documentation:

> Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Like this:

const actors = (state = initialActors, action) => {
    switch(action.type){
        case 'ADD_NEW':
            return {
                ...state,
                actors: [
                    ...state.actors,
                    {  
                       name: action.name,
                       involved: action.involved
                    }
                ]
            }
        default:
            return state
    }
}

Consider the following:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var array = [
  {  
    name: &#39;someone&#39;,
    involved: false,
  }
];

console.log([...array, { name: &#39;hello&#39;, involved: true }]);

<!-- end snippet -->

I hope this helps!

答案3

得分: 0

state.list 是一个字符串,你正尝试进行拓展

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
let a = 'name'
let c = {...a}
console.log(c)

<!-- end snippet -->

运行上述代码片段,你将能够理解它

对于添加新对象,你需要更新 reducer 如下

...state,
actors: [
...state.actors,
{
name: action.name,
involved: action.involved
}
]


因此,上述代码将会展开状态中的所有现有属性,然后你会展开所有当前的 actors 并添加一个新对象,如上所示

更新

由于你传递的是

store.dispatch(addNew({name: "Hello", involved: true}));


这里的 payload 是一个对象,所以你可以直接使用它

因此,在 action 中,它将是一个具有两个属性的对象,一个是

- type
- 你发送的 payload

...state,
actors: [
...state.actors,
action.payload
]


示例代码见 [codesandbox][1]

  [1]: https://codesandbox.io/s/59580383-so-adding-new-element-reducer-vkgyn
英文:

state.list is a string, and you are trying to spread it

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let a = &#39;name&#39;
let c = {...a}
console.log(c)

<!-- end snippet -->

run the above code snippet so you will be able to understand it

and for adding new object you need to update the reducer as follows

                ...state,
                actors: [
                    ...state.actors,
                    {  
                       name: action.name,
                       involved: action.involved
                    }
                ]

so the above code will spread all the existing properties in the state and then you spread all the current actors and add a new object as shown above

Update

Since you are passing as

store.dispatch(addNew({name: &quot;Hello&quot;, involved: true}) );

here the payload is an object so you can directly use that one

so in action it will be object which has two props one is

  • type

  • the payload you have send it

                     ...state,
                     actors: [
                         ...state.actors,
                         action.payload
                     ]
    

Sample Working codesandbox

huangapple
  • 本文由 发表于 2020年1月3日 22:34:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定