将收藏产品的 id 添加到本地存储(数组)

Add ids of Favorite products to localstrorage (array)

我在 React 和 Star 图标中有一个产品 class 可以将产品添加到收藏夹。我将最喜欢的产品 ID 存储在本地存储中。但是当我点击新产品时,previouos id 被替换为新产品 id。如何将收藏夹产品的 ID 存储在数组中? 这是我的代码:

 class Product extends React.Component {
  state = {
    favIconActive: false,
    iconColor: "black",
  };

  addToCart = () => {
    this.props.onClick();
    localStorage.setItem("Cart", this.props.card.sku);
  };

  addToFavourites = () => {
    if (this.state.favIconActive) {
      this.setState({ favIconActive: false });
      localStorage.removeItem("Favorites", this.props.card.sku);
    } else {
      this.setState({
        favIconActive: true,
      });
      localStorage.setItem("Favorites", this.props.card.sku)
    }
  };

  render() {
    const {
      card: { name, price, imgUrl, sku, color },
    } = this.props;
    return (
      <li className={styles.product}>
        <h3>{name}</h3>
        <div className={styles.imgContainer}>
          <img src={imgUrl} width="200" height="auto" alt="laptop" />
        </div>
        <span className={styles.color}>Color: {color}</span>
        <span className={styles.price}>Price: {price} $</span>
        <span className={styles.fav} onClick={this.addToFavourites}>
          <FontAwesomeIcon
            icon={faStar}
            color={localStorage.getItem(JSON.parse(sku)) ? "orange" : "black"}
          />
        </span>
        <span>SKU: {sku}</span>
        <Button text="Add to cart" color={"black"} onClick={this.addToCart} />
      </li>
    );
  }
}

您最喜欢的产品 ID 必须存储在一个数组中。

 addToFavourites = (id) => {
    if (this.state.favIconActive) {
      this.setState({ favIconActive: false });
      let favorites = JSON.parse(localStorage.getItem("Favorites"));
      let index = favorites.findIndex(productId => productId === id);
      favorites.splice(index, 1);
      localStorage.setItem("Favorites", JSON.stringify(favorites));
    } else {
      this.setState({
        favIconActive: true,
      });
      let favorites = JSON.parse(localStorage.getItem("Favorites"));
      favorites.push(id);
      localStorage.setItem("Favorites", JSON.stringify(favorites));
    }
  };

您可以创建一个状态来存储单击收藏夹图标的元素的索引,而不是为特定状态存储 true 或 false。 查看 this 博客以供参考