如何将inCart值存储在localStorage中?

时间:2019-12-22 04:29:12

标签: reactjs

在我的React ECommerce项目中,我创建了“添加到购物车”图标,当单击禁用时,该图标替换为“在购物车中”文本,表明该产品在购物车中可用,但是问题在于刷新浏览器时“购物车中”文本消失,并且购物车图标又回来了。如何将其存储在localStorage中,以便即使刷新也可以保留该值。以下是参考代码。

ProductList.js

<ProductConsumer>
  {value => {
    return value.products.map((product, key) => {
      return  <Product key={product.id} product={product} />;
    });
  }}
</ProductConsumer>

Product.js

export default function Product(props) {
  // Taken from ProductList.js File
  const {id, title, img, price, inCart} = props.product;

  <ProductConsumer>
    {(value) => (
      <button className="cart-btn" disabled={inCart?true:false}
        onClick={() => {value.addToCart(id)}}>
        { inCart ? (
          <p className="text-capitalize mb-0" disabled>
            {" "}
            In Cart</p>
        ) : (
          <i className="fas fa-shopping-cart"/>
        )}
      </button>
    )}
  </ProductConsumer>
}

context.js(定义了addToCart(id))

const ProductContext = React.createContext();

class ProductProvider extends Component {

  addToCart = (id) => {
    let tempProducts = [...this.state.products];
    const index = tempProducts.indexOf(this.getItem(id));
    const product = tempProducts[index];

    // How to store this value 'product.inCart' in...
    // ...localStorage and make it true until the product is
    // removed
    product.inCart = true;
    product.count = 1;
    const price = product.price;
    product.total = price;
    this.setState(() => {
        return { 
          products: tempProducts,
          cart: [...this.state.cart, product]
        };
      },
      () => {
        this.addTotal();
        localStorage.setItem('myCart', JSON.stringify(this.state.cart));
      });
  }

}

const ProductConsumer = ProductContext.Consumer;

export { ProductProvider, ProductConsumer };

如上图所示,当产品处于购物车中时,购物车图标被禁用,我想使inCart为true(即使刷新浏览器时),直到并且除非从购物车中移除了该产品。注意沙盒链接:https://codesandbox.io/s/mobile-store-tdgwm

添加了文件ProductList.js,并从context.js定义了ProductConsumer

1 个答案:

答案 0 :(得分:2)

在您的setProducts函数的 context.js

  setProducts = () => {
    let tempProducts = [];
    let activeProducts = JSON.parse(localStorage.getItem("myCart"));

    storeProducts.forEach(item => {
      let singleItem = { ...item };

      if(activeProducts){
         activeProducts.forEach(i => {
         if (singleItem.id === i.id) {
           singleItem = i;
         }
       });
      }

      tempProducts = [...tempProducts, singleItem];
    });

    this.setState(() => {
      return { products: tempProducts };
    });
  };

工作代码沙盒-Microsoft link - Editing Code