gpt4 book ai didi

javascript - reducer - 添加新元素

转载 作者:行者123 更新时间:2023-12-02 22:10:20 24 4
gpt4 key购买 nike

我有这家商店:

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

我有一个 reducer 来向我的商店添加新 Actor :

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

我也有一个 Action 创建者,但这并不重要。我发送它并显示我的状态:

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

console.log 显示非常困难的对象,其字母如下:{0: "A", 1: "c"}。怎么了?

@编辑我尝试将 ...state.list 更改为状态列表,如下所示:

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


default:
return state
}
}

但是我有这个错误:

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
}

]
}

错误消息与此相同,但指向操作对象(action.name)。

最佳答案

在您的 reducer 中,您错误地传播了state.list。由于它是一个字符串,因此您将获得所有字母。您应该将 state 传播到那里。因为,您希望保留 state,而不是 actors 数组。这就是为什么您传播整个状态并保留列表(如果有的话,与其他人一起)。

此外,您添加的项目错误,它应该是一个对象。

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;
}
};

关于javascript - reducer - 添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com