gpt4 book ai didi

javascript - Reducer 不知道我在 React Redux 中的状态

转载 作者:行者123 更新时间:2023-11-28 17:49:14 24 4
gpt4 key购买 nike

我正在尝试编写一个应用程序,用户可以在其中将项目添加到集合中。用户输入集合项的名称,就会出现具有该名称的项。但是当我调度操作 addCollection 时:

export function addCollection(text) {
console.log("ACTION ADD COLLECTION FIRED");
return {
type: "ADD_COLLECTION",
text
}
}

到我的 reducer :

export default function collection(state = [], action) {
switch(action.type) {
case "ADD_COLLECTION":
return (
Object.assign({}, state, {
collections: [
{
name: action.text,
src:''
},
...state.collections
]
})
);

}
return state
}

发生错误:

TypeError: Cannot convert undefined or null to object

它到达了我的 reducer 中的第 6 行。我认为reducer不知道我的state.collection

var initialState = {
collections:[
{
name:"Aenean in justo ante",
src: ''
},
{
name:"Aenean in justo ante",
src: ''
}
],
formIsRender: false
}

const store = createStore(allReducers, initialState)

哪里错了?

最佳答案

您的初始状态是一个数组,而不是一个对象
您不能也不应该在数组上使用 Object.assign
您可以通过 spread operator 使用为了不改变数组。

试试这个:

 case "ADD_COLLECTION":
return [...state, {name: action.text}]

我注意到的另一件事是,在您的初始状态对象中,您将其命名为 collections (复数),而您的 reducer 的名称为 collection (单数)。
确保它没有拼写错误。

关于javascript - Reducer 不知道我在 React Redux 中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944873/

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