reactjs 如何在react中添加本地存储数据

r6hnlfcb  于 2023-01-05  发布在  React
关注(0)|答案(2)|浏览(121)

我是阿尔斯兰乔杜里。目前,我在一个电子商务网站上工作,我将在本地存储数据,因为我没有太多的后端知识。我如何可以添加像删除和更新另一个文件夹的功能。我的代码如下所示。

图书.js

import React from "react";
import "./components/book.css";
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
import { FaShoppingCart } from "react-icons/fa";
import { useEffect } from "react";
import { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { createContext } from "react";
const Books = () => {
  let arr=()=>{
    let dat=localStorage.getItem("products")
    if (dat) {
      return JSON.parse(dat)
    }
    else{
      return []
    }
  }
  const [booksData, setbooksData] = useState([]);
  const [productData, setproductData] = useState(arr());

 
  
  let nav = useNavigate();
  // slider 
  const responsive = {
    superLargeDesktop: {
      breakpoint: { max: 4000, min: 3000 },
      items: 5,
    },
    desktop: {
      breakpoint: { max: 3000, min: 1024 },
      items: 3,
    },
    tablet: {
      breakpoint: { max: 1024, min: 464 },
      items: 2,
    },
    mobile: {
      breakpoint: { max: 464, min: 0 },
      items: 1,
    },
  };
  let croser = useRef("");
  let loding = useRef("");
  
  const getJason = async () => {
    try {
      let fea = await fetch(
        "https://script.google.com/macros/s/AKfycbxFCG7S-kjncQZwvcMnqq4wXoBAX8ecH1zkY2bLP7EE-YHlnKbiJ3RUuHtWLe6sIK30Kw/exec"
      );
      let acData = await fea.json();
      let itemsData = acData.shop.filter((element) => {
        if (element.name) {
          return element;
        }
      });
      setbooksData(itemsData);

      if (itemsData) {
        croser.current.style.filter = "blur(0px)";
        loding.current.style.display = "none";
      }
    } catch (error) {
   
      croser.current.style.filter = "blur(0px)";
      loding.current.style.display = "none";
    }
  };
  // get product data from api
  useEffect(() => {
    getJason();
  }, []);
  // go to cart button
  const goto = () => {
    nav("/Cart");
  };
// local data
let addNow=(e)=>{
let data=productData.find((element)=>{return element.id === e.id });
let cart;
if (data) {
  cart=productData.map((element)=>{
  return  element.id === e.id ? {...element, quantity:element.quantity+1}:element
  })
  
}
else{
  cart=[...productData,{...e, quantity:1}]
}
setproductData(cart);
};
useEffect(() => {
  localStorage.setItem("products",JSON.stringify(productData))
  
}, [productData])
console.log(productData);
  return (
    <>
      <div className="row " style={{ marginTop: "10px" }}>
        <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
          <div className="section-headline text-center">
            <h2>Books Shop</h2>
          </div>
        </div>
      </div>

      <div className="lodingBooks" ref={loding}>
        <div class="spinner-border" role="status"></div>
        <h4>Please wait....</h4>
      </div>

      <div ref={croser}>
        <div className=" shadow go_to_cart" onClick={goto}>
          <i class="bi bi-cart-check text-white"></i>
        </div>

        <Carousel responsive={responsive} className="container">
          {booksData.map((element) => {
            return (
              <>
                <div class="container page-wrapper">
                  <div class="page-inner">
                    <div class="row">
                      <div class="el-wrapper">
                        <div class="box-up">
                          <img class="img" src={element.images} alt="" />
                          <div class="img-info">
                            <div class="info-inner">
                              <span class="p-name text-info">
                                {element.name}
                              </span>
                              <span class="p-company ">Author:CHAUDHRY</span>
                            </div>
                            <div class="a-size ">
                              About:This is a complete book on javascript
                              <span class="size"></span>
                            </div>
                          </div>
                        </div>
                        <input
                          type="text"
                          value={1}
                          style={{ display: "none" }}
                        />
                        <div class="box-down">
                          <div class="h-bg">
                            <div class="h-bg-inner"></div>
                          </div>

                          <a class="cart">
                            <span class="price">{element.price + "$"}</span>

                            <span
                              class="add-to-cart btn btn-sm"
                              style={{ backgroundColor: "#3EC1D5" }}
                              onClick={()=>{addNow(element)}}
                            >
                              <span class="txt">
                                ADD TO CART <FaShoppingCart />
                              </span>
                            </span>
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </>
            );
          })}
        </Carousel>
      </div>
    </>
  );
};

export default Books;

**这里是我的购物车文件。我想在这里执行更新和删除等操作。**Cart.js

import React from "react";
import "./components/cart.css";
import { useEffect } from "react";
const Cart = () => {
  let data = localStorage.getItem("products");
  let javaData = JSON.parse(data);
  let removeData = (e) => {
    
   
  };
useEffect(() => {
  localStorage.clear()
}, [])

  return (
    <>
      <div class="container mt-5 mb-5">
        <div class="d-flex justify-content-center row">
          <div class="col-md-8">
            <div class="p-2 shoingTitle">
              <h4>Shop Now</h4>
              <span class="text-danger">Remove all</span>
            </div>
            {javaData ? (
              javaData.map((item) => {
                return (
                  <>
                    <div class="d-flex flex-row justify-content-between align-items-center p-2 bg-white mt-4 px-3 rounded">
                      <div class="mr-1 imageandpara">
                        <img class="rounded" src={item.images} width="70" />
                        <span class="font-weight-bold">{item.name}</span>
                      </div>
                      <div class="d-flex flex-column align-items-center product-details">
                        <div class="d-flex flex-row product-desc"></div>
                      </div>
                      <div class="d-flex flex-row align-items-center qty">
                        <i class="minusSign shadow">
                          <i class="bi bi-dash"></i>
                        </i>
                        <span class="text-grey quantityNumber">
                          {item.quantity}
                        </span>
                        <i class="minusSign shadow">
                          <i class="bi bi-plus"></i>
                        </i>
                      </div>
                      <div>
                        <span class="text-grey productAmount">{`${
                          item.quantity * item.price
                        }$`}</span>
                      </div>
                      <div
                        class="d-flex align-items-center text-dark "
                        style={{
                          cursor: "pointer",
                          fontWeight: "900",
                          fontSize: "15px",
                        }}
                        onClick={() => {
                          removeData(item);
                        }}
                      >
                        <i class="bi bi-x text-danger"></i>
                      </div>
                    </div>
                  </>
                );
              })
            ) : (
              <h3 style={{ textAlign: "center" }}>Cart is empety</h3>
            )}

            <div class="d-flex flex-row align-items-center mt-3 p-2 bg-white rounded">
              <input
                type="text"
                class="form-control gift-card "
                placeholder="discount code/gift card"
              />
              <button
                class="btn  btn-sm ml-3 shadow"
                type="button"
                style={{
                  outline: "#3EC1D5",
                  backgroundColor: "#3EC1D5",
                  color: "white",
                }}
              >
                Apply
              </button>
            </div>
            <div class="totalItems">
              Total Items: <strong>12</strong>
            </div>
            <span class="TotalPrice">
              Total price: <strong>12$</strong>
            </span>
            <div class="d-flex flex-row align-items-center mt-3 p-2 bg-white rounded">
              <button
                class="btn  btn-block btn-sm ml-2 pay-button shadow"
                type="button"
                style={{ backgroundColor: "#3EC1D5" }}
              >
                Proceed to Pay
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Cart;
gojuced7

gojuced71#

尝试添加以下内容:

let removeData = (e) => {
    localStorage.setItem("name of the item") // e.target.name
  };
zvms9eto

zvms9eto2#

有很多事情发生在您的网站:)我认为它将负责创建一个上下文,这将服务于所有其他组件的购物车。这里要注意的事情,(发现一些小改进)

  • 运行useState钩子中的函数,不要像以前那样将其留在那里
  • 当使用Array.filter时,你需要为它返回一个布尔iorder,以便正确地过滤你的数组。

这是我带来的代码,希望它能帮助你. CartContext.js文件.

import React, { createContext, useContext, useEffect, useState } from "react";

export const CartContext = createContext();
function Cart({ children }) {
  const arr = useCallback(() => {
    let dat = localStorage.getItem("products");
    if (dat) {
      return JSON.parse(dat);
    } else {
      return [];
    }
  }, []);

  const [productData, setproductData] = useState(() => arr());

  const getJason = async () => {
    try {
      let fea = await fetch(
        "https://script.google.com/macros/s/AKfycbxFCG7S-kjncQZwvcMnqq4wXoBAX8ecH1zkY2bLP7EE-YHlnKbiJ3RUuHtWLe6sIK30Kw/exec"
      );
      let acData = await fea.json();
      //   filter callback function should return a boolean. That is either true or false in order to make it work.
      // SO i think this function isn't going to function properly
      let itemsData = acData.shop.filter((element) => {
        if (element.name) {
          return element;
        }
      });
      setbooksData(itemsData);

      if (itemsData) {
        croser.current.style.filter = "blur(0px)";
        loding.current.style.display = "none";
      }
    } catch (error) {
      croser.current.style.filter = "blur(0px)";
      loding.current.style.display = "none";
    }
  };

  // get product data from api
  useEffect(() => {
    getJason();
  }, []);

  const addProduct = (e) => {
    // check if product id available on cart
    const findProduct = productData.find((element) => {
      return element.id === e.id;
    });
    // add first quantity if not available
    if (!findProduct)
      return setproductData([...productData, { ...e, quantity: 1 }]);
    // increase quantity by 1
    const newCart = productData.map((element) => {
      return {
        ...element,
        quantity: element.id === e.id ? element.quantity + 1 : element.quantity,
      };
    });
    setproductData(newCart);
  };

  const removeProduct = (e) => {
    // check if product id available on cart
    const findProductQuantity = productData.find((element) => {
      return element.id === e.id && element.quantity >= 1;
    });
    // add first quantity if not available
    if (!findProduct)
      // Your ui should prevent this
      return;
    // decrease quantity by 1
    const reducedQuantityCart = productData.map((element) => {
      return {
        ...element,
        quantity: element.id === e.id ? element.quantity - 1 : element.quantity,
      };
    });
    // filter out all products with quantity less than 1 (quantity : 0)
    const newCart = productData.filter((element) => {
      return element.quantity >= 1;
    });
    setproductData(newCart);
  };

  const deleteProduct = (e) => {
    // check if product id available on cart
    const findProduct = productData.find((element) => {
      return element.id === e.id;
    });
    // add first quantity if not available
    if (!findProduct)
      // Your ui should prevent this
      return;
    const productIndex = productData.findIndex((element) => {
      return element.id === e.id;
    });
    // splice (delete) product from the productData array
    const newCart = [productData].splice(productIndex, 1);
    setproductData(newCart);
  };

  const value = {
    productData,
    addProduct,
    removeProduct,
    deleteProduct,
  };

  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

在这里,您可以创建上下文,创建用于更新购物车的所有函数,并将它们传递给上下文提供程序

// create a hook can you use anywhere in the app
export const useCart = () => {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error("Must use useCart in CartContext Child");
  }
  const { productData, addProduct, removeProduct, deleteProduct } = context;
  return { productData, addProduct, removeProduct, deleteProduct };
};

为此,您需要创建一个自定义钩子,只要它是Cart上下文的子组件,您就可以在任何组件中使用它。

// Use Case
const SomeComponent = () => {
  const { productData, addProduct, removeProduct } = useCart();
  return (
    <div>
      <p> Number of Products: {productData.length}</p>
      <div>
        {productData?.map((product) => (
          <div>
            <p>{product?.name}</p>
            <button onClick={() => addProduct(product)}>add</button>
            <button onClick={() => removeProduct(product)}>
              subtract/reduce
            </button>
            <button onClick={() => deleteProduct(product)}>delete</button>
          </div>
        ))}
      </div>
    </div>
  );
};

用例场景od这段代码将如何工作。希望你觉得这有帮助

相关问题