[英]React Native getting error “Invalid attempt to spread non-iterable instance.” while adding data to empty array
Trying to add the data in empty array but getting below error in BlogContext file while calling addBlogPost from adddata screen:尝试在空数组中添加数据,但在从 adddata 屏幕调用 addBlogPost 时在 BlogContext 文件中出现以下错误:
Invalid attempt to spread non-iterable instance.传播不可迭代实例的无效尝试。 In order to be iterable, non-array objects must have a Symbol.iterator method.
为了可迭代,非数组对象必须具有 Symbol.iterator 方法。 - node_modules/@babel/runtime/helpers/nonIterableSpread.js:2:22 in _nonIterableSpread - node_modules/@babel/runtime/helpers/toConsumableArray.js:10:111 in _toConsumableArray * src/context/BlogContext.js:6:8 in blogReducer
- node_modules/@babel/runtime/helpers/nonIterableSpread.js:2:22 in _nonIterableSpread - node_modules/@babel/runtime/helpers/toConsumableArray.js:10:111 in _toConsumableArray * src/context/BlogContext.js:6:8在博客减速机
below is code for BlogContext下面是 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 },
[]
);
const blogReducer = (state, action)
state here is undefined at the begining so try this state 这里一开始是未定义的,所以试试这个
const blogReducer = (state = [], action)
Its working fine now,, i am doing mistake in below code:它现在工作正常,我在下面的代码中犯了错误:
export const { Context, Provider } = createDataContext(
blogReducer,
{ addBlogPost },
{ deleteBlogPost },
[]
);
these { addBlogPost }, { deleteBlogPost }, two should be in same object like {addBlogPost, deleteBlogPost}, only this change make it work, Thanks for all the help这些 { addBlogPost }, { deleteBlogPost },两个应该在同一个 object 中,如 {addBlogPost, deleteBlogPost},只有这个更改才能工作,感谢所有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.