[英]Need to delete item from array using redux
so I have a reducer that is adding to array create reducer : 所以我有一个reducer添加到数组create reducer:
export default (itemsList = [], action) => {
if (action.type === 'ADD_ITEM') {
return [...itemsList, action.payload]
}
return itemList
}
deleting reducer (99% that something is wrong here, but I have no idea what ): 删除reducer(99%的地方这里有问题,但我不知道是什么):
export default (itemList = [], action) => {
if (action.type === 'DELETE_ITEM') {
return [...itemList, itemList.filter(item => item !== action.payload)]
}
return itemList
};
action/index.js: 动作/ index.js:
export const addItemToList = item => {
return {
type: 'ADD_ITEM',
payload: selectedItem
}
};
export const deleteItemFromList = item => {
return{
type: 'DELETE_ITEM',
payload: selectedItem
}
};
let say I have itemList = [ 'abc', 'xyz', 'qwe' ] 假设我有itemList = ['abc','xyz','qwe']
and I want to use deleteItem('xyz') to delete 'xyz' from itemList 我想使用deleteItem('xyz')从itemList删除'xyz'
While deleting you just need to return the filtered list and not use spread operator too. 删除时,您只需要返回过滤后的列表即可,也不要使用传播运算符。
export default (itemList = [], action) => {
if (action.type === 'DELETE_AUTHOR') {
return itemList.filter(item => item !== action.payload)
}
return listOfAuthorsSelected
};
Array.filter() returns a new array with given filter condition and not mutate the existing array. Array.filter()返回具有给定过滤条件的新数组,并且不对现有数组进行突变。 You don't have need to use ...itemList
(spread operator). 您无需使用...itemList
(传播运算符)。 Here you are actually adding a sub array each time. 实际上,您实际上每次都在添加一个子数组。
Here is a simple running example 这是一个简单的运行示例
var array1 = ["abc", "def" , "ghi"]; var array2 = [...array1, array1.filter((item) => { return item !== "def" })]; document.write(array2); // correct way to filter var array3 = ["abc", "def" , "ghi"]; var array4 = array3.filter((item) => { return item !== "def" }); document.write("<hr/>"+array4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.