简体   繁体   English

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

[英]Why is my original state mutated when filtering with react redux

im using redux in an react app. 即时通讯在React应用程序中使用redux。 Why is this filtering func mutating the original state.products? 为什么此过滤函数会改变原始state.product? I cant understand why 我不明白为什么

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 will have only products that is active but the state.products is also updated containing only active products when trying to filter on the same data again. filteredItems将仅具有活动产品,但state.products也将更新,仅在尝试再次过滤相同数据时才包含活动产品。

Suggestions 意见建议

Because you're assigning to a property on an existing state item: 因为您要分配给现有状态项目上的属性,所以:

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
  };
}

Instead, create a new item to return. 而是创建一个项目以返回。 Also, it looks like you need map along with filter , and you're not actually returning item.active in your inner filter (see this question's answers for more there): 另外,看起来您需要mapfilter ,并且实际上item.active在内部filter 返回 item.active (有关更多信息,请参阅此问题的答案 ):

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
  };
}

Side note: This: 旁注:此:

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

can be simply: 可以很简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM