简体   繁体   English

如何将数量保存到本地存储

[英]how can i save quantity to local storage

working on a cart app - when the quantity gets bought it supposed to make the button disabled but if I refresh it becomes active again , anyone knows how to save it to local storage?在购物车应用程序上工作-当购买数量时,它应该使按钮禁用,但如果我刷新它再次变为活动状态,有人知道如何将其保存到本地存储吗?

import { Button } from 'react-bootstrap';
import { Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useContext } from 'react';
import Rating from './Rating';
import axios from 'axios';
import { Store } from '../Store';

function Product(props){

    const {product} = props;

    const {state , dispatch:ctxDispatch} = useContext(Store);
    const {cart: {cartItems}} = state

    const addToCartHandler = async (item )=>{
      const existItem = cartItems.find((x)=> x._id === product._id);
       const quantity = existItem ? existItem.quantity+1:1 ; 

      const {data} = await axios.get(`/api/products/${item._id}`);
      if(data.countInStock < quantity){
          window.alert('sorry product is out of stock')
          return;
      }
  product.countInStock--
       ctxDispatch({
           type:'CART_ADD_ITEM' 
           , payload:{...item , quantity},
       });
      };
      

    return(

        <Card>


        <Link to={`/product/${product.slug}`}> 
          <img src={product.image} className="card-img-top" alt={product.name} />
        </Link>
        <Card.Body>
        <Link to={`/product/${product.slug}`}>
            <Card.Title>{product.name}</Card.Title>
        </Link>
        <Rating rating={product.rating} numReviews={product.numReviews} />
        <Card.Text>${product.price}</Card.Text>

        {  product.countInStock === 0 ? (

          
          <Button  color="light" disabled={true} >  Out of stock</Button>
          
        ):(
          
          <Button onClick={() => addToCartHandler(product)}>Add to cart</Button>
        )}
      </Card.Body>
    </Card>
    )}

product.countInStock is what needed to be saved to local storage product.countInStock 是需要保存到本地存储的

我认为您应该为禁用状态声明一个变量,例如 disabled={disabledState} 以便您可以控制按钮的禁用,在 localStorage 中设置某些内容只需在 onClick 事件处理程序 window.localStorage.setItem('',') 上使用它

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

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