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

hea*_*row 1 javascript filter reactjs 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
 };
}
Run Code Online (Sandbox Code Playgroud)

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

意见建议

T.J*_*der 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
  };
}
Run Code Online (Sandbox Code Playgroud)

而是创建一个项目以返回。另外,看起来您还需要mapfilter,并且实际上 没有返回item.active内部filter(有关更多信息,请参见此问题的答案):

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
  };
}
Run Code Online (Sandbox Code Playgroud)

旁注:此:

products: item.products.filter((item) => {
  return item.active;
})
Run Code Online (Sandbox Code Playgroud)

可以很简单:

products: item.products.filter(({active}) => active)
Run Code Online (Sandbox Code Playgroud)