简体   繁体   English

如何在React中从购物车状态中删除未选中的项目

[英]How to remove unchecked items from cart state in React

I have items displayed with check boxes and once clicked/checked they are added to the cart. 我有显示带有复选框的项目,一旦单击/选中,它们便被添加到购物车中。 When unchecked they are added to the cart again. 取消选中时,它们会再次添加到购物车中。 I am not sure how to toggle the checked to remove the item when unchecked. 我不确定如何取消选中时如何切换选中状态以删除该项目。

export class DestinationPrices extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      flightData: [],
      isChecked: props.isChecked || false,

      data: "",
      cart: []
    };

    this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
  }

  // ...
}

Select(FD) {
  return (
    <div>
      {FD.FlightID}
      <label>
        <Checkbox
          id={FD.FlightID}
          name={FD.FlightID}
          value={this.state.isChecked}
          onChange={() => this.handleCheckboxChange(FD)}
        />
        <span>Select</span>
      </label>
    </div>
  );
}
handleCheckboxChange = id => {
  const cartItem = this.state.cart.filter(x => x.FlightID === id.FlightID);

  this.setState({
    isChecked: !this.state.isChecked,
    cart: [...this.state.cart, id]
  });
}

When the item is checked, it displays in the cart with some details. 选中该项目后,它将显示在购物车中,并带有一些详细信息。 With every click of the checkbox, the item adds to state and shows in the card, regardless if it is checked or unchecked. 每次单击复选框,该项目都会添加到状态并显示在卡中,无论是否选中该项目。 I need to delete the item from state if the item is unchecked. 如果未选中该项目,则需要从状态中删除该项目。

Do I check if the item is already there and delete from cart? 我要检查商品是否已经存在并从购物车中删除吗?

render() {
  var data = this.props.cart;

  var arry = [];
  arry.push(data);

  return (
    <div>
      <Card body>
        <CardTitle>
          <h3>
            <b>Flights Selected : </b>
          </h3>
        </CardTitle>

        <CardText>
          <span className="fa fa-cart-plus fa-2x"> {data.length} </span>{" "}
          {this.getData()}
        </CardText>

        <div />
      </Card>
    </div>
  );
}

Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!

One way of going about it is to do how you outlined in your question: check if the item already is in the cart. 解决它的一种方法是按照问题的方式进行处理:检查商品是否已经在购物车中。 If it is, you can remove it from the cart. 如果是这样,您可以将其从购物车中删除。 It it's not, you can add it to the cart. 并非如此,您可以将其添加到购物车中。

handleCheckboxChange = item => {
  this.setState(prevState => {
    const isItemInCart = prevState.cart.some(el => el.FlightID === item.FlightID);
    const cart = isItemInCart
      ? prevState.cart.filter(el => el.FlightID !== item.FlightID)
      : [...prevState.cart, item];

    return { cart };
  });
}

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

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