为什么在使用React Redux进行过滤时我的原始状态会发生变化

时间:2019-05-17 09:56:57

标签: javascript reactjs filter redux

我在React应用中使用Redux。为什么此过滤函数会改变原始state.product?我不明白为什么

state.products = [
   { 
      type: "one",
      products: [
         { active: true },
         { active: false }
     ]
  }
 ]

function mapStateToProps(state) {
 const test = state.products.filter((item) => {
   if(item.type === "one") {
     return item.products = item.products.filter((item) => {
       item.active
      });
    }
    return item;
  });

  return {
    machineSearchWeightRange: state.machineSearchWeightRange,
    filteredItems: test //This will have only products active
 };
}

filteredItems将仅具有活动产品,但state会更新,当尝试再次过滤相同数据时,products也仅包含活动产品。

建议

1 个答案:

答案 0 :(得分:5)

因为您要分配给现有状态项目上的属性:

function mapStateToProps(state) {
  const test = state.products.filter((item) => {
    if(item.type === "one") {
      return item.products = item.products.filter((item) => { // <========== Here
        item.active
       });
     }
     return item;
   });

   return {
     machineSearchWeightRange: state.machineSearchWeightRange,
     filteredItems: test //This will have only products active
  };
}

相反,创建一个 new 项返回。此外,您似乎还需要mapfilter,实际上并没有在内部item.active返回 filter(请参见{ {3}},以了解更多信息):

function mapStateToProps(state) {
  const test = state.products.filter(({type}) => type === "one").map(item => {
    return {
        ...item,
        products: item.products.filter((item) => {
          return item.active;
        })
    };
  });

  return {
    machineSearchWeightRange: state.machineSearchWeightRange,
    filteredItems: test //This will have only products active
  };
}

旁注:此:

products: item.products.filter((item) => {
  return item.active;
})

可以很简单:

products: item.products.filter(({active}) => active)