【问题标题】:How to remove an object from Array in ReactReact 如何从数组中删除一个对象
【发布时间】:2020-12-31 11:13:11
【问题描述】:

我对这些东西不熟悉,但我对学习它充满热情。因此,请随意链接文档,我很乐意查找它们。我在 Reactjs 中构建了一个购物车列表组件。我实现了 addToCart 和 removeFromCart 函数。问题在于 removeFromCart 函数。我有一个 json 文件,我可以从中获取我的类别和产品。我有 onClick 声明,可以更改组件的状态并呈现所需类别的新产品列表。我添加了一个从购物车中删除产品的按钮,但该按钮只会减少产品的数量。我想在产品数量降至零以下时移除产品。这是我的代码,希望对你有所帮助。

 changeCategory = (category) => {
    this.setState({ currentCategory: category.categoryName });
    this.getProducts(category.id);
  };
   resetCategory = (category) => {
     this.setState({currentCategory: "",});
     this.getProducts()
   };
  getProducts = (categoryId) => {
    let url = "http://localhost:3000/products";
    if (categoryId) {
      url += "?categoryId=" + categoryId;
    }
    fetch(url)
      .then((response) => response.json())
      .then((data) => this.setState({ products: data }));
  };
  addToCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem) {
      addedItem.quantity += 1;
    } else {
      newCart.push({ product: product, quantity: 1 });
    }

    this.setState({ cart: newCart });
    alertify.success(product.productName + " added to the cart.,", 2);
  };

这是组件的状态:

state = {
    currentCategory: "",
    products: [],
    cart: [],
  };

最后是有问题的部分:

removeFromCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem) {
      addedItem.quantity -= 1;
    } 
    // var zeroItem = addedItem.quantity ;
    // zeroItem = newCart.filter((a) => a.addedItem.quantity !== 0)
    // this.state.zeroItem.filter((c) => c.product.id !== product.id);
    this.setState({ cart: newCart });
    alertify.error(product.productName + " removed from the cart.", 2);
  };

评论部分是我尝试过的,但显然它们没有用。当产品数量降至零以下时,如何在此类项目中删除产品? 提前谢谢大家。

对于那些愿意提供帮助的人:减少数量我没有问题。当addedItem 的数量低于0 时,我只需要一种方法来删除该特定对象。

【问题讨论】:

标签: javascript arrays reactjs


【解决方案1】:

您可以简单地使用过滤器从数组中删除一个项目。

    removeFromCart = (product) => {
        let newCart = this.state.cart;
        var addedItem = newCart.find((c) => c.product.id === product.id);
        if (addedItem && addedItem.quantity > 1) {
            addedItem.quantity -= 1;
        } else {
            newCart = newCart.filter(({ id }) => id === product.id)
        }
        // var zeroItem = addedItem.quantity ;
        // zeroItem = newCart.filter((a) => a.addedItem.quantity !== 0)
        // this.state.zeroItem.filter((c) => c.product.id !== product.id);
        this.setState({ cart: newCart });
        alertify.error(product.productName + " removed from the cart.", 2);
  };

我只是稍微编辑了您的代码,现在它就像一个魅力。您可以在下面看到我的修订版。

 removeFromCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem && addedItem.quantity > 1) {
        addedItem.quantity -= 1;
    } else {
        newCart = newCart.filter((c) => c.product.id !== product.id);
        this.setState({ cart: newCart });
    }
    this.setState({ cart: newCart });
    alertify.error(product.productName + " removed from the cart.", 2);
  };

【讨论】:

  • 感谢您的回复。这适用于减少,但是当产品数量低于零时,它会擦除​​整个购物车。
【解决方案2】:
removeFromCart = (product) => {
  let {cart}=this.state;
  let {quantity:currentQuantity} = cart.find(pr => pr.product ===product)
  if(currentQuantity > 1) {
    this.setState(prevState => 
      ({cart : [...prevState.cart.filter(pr => pr.product !== product), {product, quantity: currentQuantity-1} ] })) 
  }
  else { 
  this.setState(prevState => 
    ({cart : prevState.cart.filter(pr => pr.product !== product) })) 
  }
}

【讨论】:

  • 哇,谢谢。最后一个问题。当我现在减少其数量时,产品的行发生了变化。有什么办法可以防止吗?
  • shouldComponentUpdate(nextProps, nextState) { if(nextState.cart.length === this.state.cart.length) { return false; } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
相关资源
最近更新 更多