如何使用复选框显示数据,取消选中后必须显示以前的状态?

问题描述 投票:0回答:1

我正在使用reactJS开发一个e-comm站点,它在侧栏中有复选框,我写了逻辑,但是它选择所有复选框并过滤产品并显示过滤后的数据但是当我取消选中时,它没有显示以前的状态。请帮助解决此问题。

   class DashView extends Component {
   constructor(props) {
   super(props);
   this.state = {
    products: [],
      isChecked: false
     };
   this.getProductList = this.getProductList.bind(this);
   // this.clearCheck = this.clearCheck.bind(this);
  }
 componentDidMount() {
  // const { isChecked } = this.state;
  let apiUrl = ` https://api.myjson.com/bins/4xc0c`;
 axios.get(apiUrl).then(res => {
  // console.log(res.data.products);
  this.setState({
    products: res.data.products,
    isChecked : this.state.isChecked
    });
   });
   }

  getProductList = item => {
  const { products, isChecked } = this.state;
  const prevProducts = this.state.products;
  console.log(products);
   // console.log(item);
  let newProduct = [];
  if ((isChecked === false && item === "smartphone") || item === "iphone") {
  for (let i = 0; i < products.length; i++) {
    if (products[i].ptype === item) {
      console.log(item);
      newProduct.push(products[i]);
    }
   }
  console.log(newProduct);
  this.setState({
    products: newProduct,
    isChecked: !isChecked
    });
   } else {
  console.log("unchecked");
  console.log(prevProducts);

  this.setState({
    prevProducts : this.state.products,
    isChecked : !isChecked
  })
  }
 }
reactjs
1个回答
0
投票

const prevProducts = this.state.products; // 不对

this.state.products包含实际渲染的数据,它被过滤后的onces覆盖

 console.log(newProduct);  // filtered
  this.setState({
    products: newProduct,  // for rendering
    isChecked: !isChecked
  });
} else {
  console.log("unchecked");
  this.setState({
    prevProducts : this.state.products, // doesn't make sense here
    isChecked : !isChecked
  })
}

它应该是:

    console.log(newProduct); // filtered
    this.setState({
      prevProducts : this.state.products,  // backup
      products: newProduct,  // for rendering
      isChecked: !isChecked
    });
  } else {
    console.log("unchecked");
    console.log(prevProducts);

    this.setState({
      products : this.state.prevProducts, // restore, not filtered
      isChecked : !isChecked
    })
  }

您也可以在加载时备份数据:

this.setState({
  products: res.data.products,  // for rendering
  prevProducts: res.data.products, // for restoring from filtering
  isChecked : this.state.isChecked
});
© www.soinside.com 2019 - 2024. All rights reserved.