javascript - Redux 比较数组的每个索引

标签 javascript reactjs redux

我试图添加一个状态,该状态假设有一个索引数组,并且每个索引都必须与状态索引进行比较并删除商店状态,例如我有一个产品的状态:

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/

相关文章:

javascript - jQuery Fancybox 不支持 post 方法中的链接

javascript - 无法读取 null 的属性 addEventListener

reactjs - 如何使用 useReducer([state,dispatch]) 和 useContext 避免无用的重新渲染?

javascript - Redux - 如何对变化做出一次 react

javascript - 如何使用 Tailwind CSS 使 'useState' 过渡更平滑

javascript - 异步函数无法使用 JQuery 工作

java - 从同一公司网站的不同域获取 cookie

node.js - Fluxible 中的“脱水”和“再水合”代表什么?

reactjs - 如何使用 Redux 文档中解释的这个高阶组件?

reactjs - Redux - 如何调用一个 Action 并等待它被解决