[英]Add Items into Empty array in Reducer give Error 'TypeError: Invalid attempt to spread non-iterable instance.'
I'm tried to declare any empty array in reducer and trying to add some objects in it dynamically.But I got this error when i try to add new item in it.'TypeError: Invalid attempt to spread non-iterable instance.'It means that you don't have any array in which you are trying to add new item?.How's it possible.Here is my reducer state.我试图在 reducer 中声明任何空数组并尝试在其中动态添加一些对象。但是当我尝试在其中添加新项目时出现此错误。'TypeError: Invalid trial to spread non-iterable instance.'It意味着您没有任何要在其中添加新项目的数组?怎么可能。这是我的减速器状态。
const initialState = {
recentSearches: [],
};
here is my function firing up这是我的功能启动
const handleItem = async (item) => {
let recent = [...recentSearches];
recent.push(item);
new Promise((rsl, rej) => {
addSearchItem(recent, rsl, rej);
})
.then((res) => {
navigation.navigate('SearchDetail', {text: item.name});
// console.log('Zaid ----->', res);
})
.catch((res) => {
console.log(res);
});
};
here is the action to reducer这是减速器的动作
export const addSearchItem = (data, rsl, rej) => {
return (dispatch) => {
try {
dispatch({
type: ADD_SEARCH,
recentSearches: data,
});
rsl();
} catch (err) {
rej();
}
};
};
here is the case这是这种情况
case ADD_SEARCH:
return {
...state,
recentSearches: action.recentSearches,
};
you can update an array in redux immutably in this way您可以通过这种方式不可变地更新 redux 中的数组
return {
...state,
recentSearches:state.recentSearches.concat(item),
}
I hope this will help for more follow this https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns我希望这将有助于更多关注这个https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
This error happens when you trying to copy an undefined array in your reducer.当您尝试在减速器中复制未定义的数组时会发生此错误。 eg:
例如:
const newList = [...state.someList];
In this case, 'someList' is undefined or not an array.在这种情况下,'someList' 未定义或不是数组。 make sure your spelling or you are using the correct array.
确保您的拼写或您使用的是正确的数组。
尚未修复 上面提供的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.