尝试在空数组中添加数据,但在从adddata屏幕调用addBlogPost时遇到BlogContext文件中的错误:
尝试传播不可迭代的实例无效。 为了可迭代,非数组对象必须具有Symbol.iterator方法。 -_nonIterableSpread中的node_modules/@babel/runtime/helpers/nonIterableSpread.js:2:22 -_toConsumableArray中的node_modules/@babel/runtime/helpers/toConsumableArray.js:10:111 * blogReducer中的src / context / BlogContext.js:6:8
以下是BlogContext的代码
import createDataContext from "./createDataContext";
const blogReducer = (state, action) => {
switch (action.type) {
case "add_blogpost":
return [
...state,
{
id: Math.floor(Math.random() * 9999),
title: action.payload.title,
content: action.payload.content,
},
];
case "edit_blogpost":
return state;
case "delete_blogpost":
return state.filter((blogPost) => blogPost.id != action.payload);
default:
return state;
}
};
const addBlogPost = (dispatch) => {
return (title, content, callBack) => {
dispatch({
type: "add_blogpost",
payload: { title: title, content: content },
});
callBack();
};
};
const deleteBlogPost = (dispatch) => {
return (id) => {
dispatch({ type: "delete_blogpost", payload: id });
};
};
export const { Context, Provider } = createDataContext(
blogReducer,
{ addBlogPost },
{ deleteBlogPost },
[]
);
答案 0 :(得分:0)
const blogReducer = (state, action)
开头的状态未定义 所以试试这个
const blogReducer = (state = [], action)
答案 1 :(得分:0)
现在工作正常,我在下面的代码中做错了:
export const { Context, Provider } = createDataContext(
blogReducer,
{ addBlogPost },
{ deleteBlogPost },
[]
);
这两个{addBlogPost},{deleteBlogPost},两个应该位于同一对象中,例如{addBlogPost,deleteBlogPost},只有此更改才能使其生效, 感谢您的所有帮助