我试图添加一个状态,该状态假设有一个索引数组,并且每个索引都必须与状态索引进行比较并删除商店状态,例如我有一个产品的状态:
state.products = [
{productName: "patric", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 2}
{productName: "parafuso", withTax: "55.50", noTax: "222.00", tax: 25, quantity: 2} //remove this
{productName: "mamao", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 5} // remove this
]
action.index = [
{productName: "parafuso", withTax: "55.50", noTax: "222.00", tax: 25, quantity: 2} //remove this
{productName: "mamao", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 5} // remove this
]
//this is not removing the selecteds items
const products = state.products.filter((product, i) => {
for(let i=0; i < action.index.length; i++){
if(product.name !== action.index[i].name) return true
}
return false
})
return {
...state,
products
}
最佳答案
我会采取类似但优化的方法。
首先,我只会提取您想要删除的产品的名称,因为对您所在州拥有的产品的每一项运行 for 查找是没有意义的。
其次,使用 indexOf
代替带有相等运算符 ===
的 for
循环执行速度更快,因为浏览器可以优化执行。
最后,尝试提高可读性。
// Given that this is your state
state.products [
{productName: "patric", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 2}
{productName: "parafuso", withTax: "55.50", noTax: "222.00", tax: 25, quantity: 2} //remove this
{productName: "mamao", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 5} // remove this
]
// Given that this is the action you dispatch
action = {
type: 'FILTER_PRODUCTS'
index: [
{productName: "parafuso", withTax: "55.50", noTax: "222.00", tax: 25, quantity: 2} //remove this
{productName: "mamao", withTax: "0.57", noTax: "2.30", tax: 25, quantity: 5} // remove this
]
}
//Reducer code...
case 'FILTER_PRODUCTS': {
// extract the names just once
const namesToRemove = action.index.map( product => product.name )
// filter the products
const products = state.products.filter( product => namesToRemove.indexOf( product.name ) === -1 )
return { ...state, products }
}
编辑
您还可以将 Array.indexOf
替换为较新的 Array.includes
。
const products = state.products.filter( product => namesToRemove.indexOf( product.name ) === -1 )
变成
const products = state.products.filter( product => ! namesToRemove.includes( product.name ) )
关于javascript - Redux 比较数组的每个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102476/