减速机不知道我的状态在反应减少
问题描述:
我想写一个应用程序,用户可以在其中添加一个项目到集合。用户键入collection-item的名称,并出现该名称的项目。 但是,当我派遣行动addCollection
:减速机不知道我的状态在反应减少
export function addCollection(text) {
console.log("ACTION ADD COLLECTION FIRED");
return {
type: "ADD_COLLECTION",
text
}
}
我减速机:
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
它有我的减速器6行。我认为减速机不知道我的状态。收集
var initialState = {
collections:[
{
name:"Aenean in justo ante",
src: ''
},
{
name:"Aenean in justo ante",
src: ''
}
],
formIsRender: false
}
const store = createStore(allReducers, initialState)
错误在哪里?
答
您的初始状态是array
而不是object
。
您不能也不应该在阵列上使用Object.assign
。
虽然可以使用spread operator以便不改变数组。
试试这个:
case "ADD_COLLECTION":
return [...state, {name: action.text}]
我注意到另一件事是,在初始状态对象将其命名为collections
(复数)和你减速的名字是collection
(单数)。
确保它不是拼写错误。