javascript useEffect钩子未运行以更新本地存储

rekjcdws  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(122)

我正在使用React创建一个电子商务网站,我在页面加载时在localStorage中设置购物车项目(用户已经选择添加到他/她的购物车中),然后使用localStorage.getItems()获取它们。
但由于某种原因,当我试图设置项目为localStorage使用useEffect挂钩,然后它不运行,我不知道为什么。我甚至试过console.log(),但也没有运行.
因此,当函数从localStorage获取项时,它会返回null
这里是代码,请帮助我。

import { createContext, useContext, useReducer, useEffect } from "react";
import { reducer } from "../reducer/CartReducer";

// creating Context using context API
const CartContext = createContext();

const getLocalCartData = () => { // this function returns null because useEffect did not run and not set  any thing to the localstorage.
  let localCartData = localStorage.getItem('CartItems');
  console.log(localCartData)
  if (localCartData === []) {
    return [];
  } else {
    return JSON.parse(localCartData);
  }
}

// Defining initial State for the useReducer
const initialState = {
  cart: getLocalCartData(),
  total_item: ""
}
const CartProvider = ({ children }) => {

  // Defining useReducer, dispatch, state  
  const [state, dispatch] = useReducer(reducer, initialState);

  // Add products to cart
  const addToCart = (MainProduct, amount) => {
    dispatch({ type: "ADD_TO_CART", payload: { MainProduct, amount } });
  };

  // Add products to cart
  const removeItem = (id) => {
    dispatch({ type: "REMOVE_ITEM", payload: id });
  };

  // Decreament Product Quantity
  const setDecreament = (id) => {
    dispatch({ type: "SET_DECREAMENT", payload: id })
  }

  // Increament Product Quantity
  const setIncreament = (id) => {
    dispatch({ type: "SET_INCREAMENT", payload: id })
  }

  useEffect(() => { // this one useEffect is not running 
    console.log("It Should run here")
    localStorage.setItem('CartItems', JSON.stringify(state.cart));   
  }, [])

  // Creating the Provider
  return (<CartContext.Provider value={{ ...state, addToCart, removeItem, setIncreament, setDecreament }}>
    {children}
  </CartContext.Provider>);
}

// Creating use context API
const useCartContext = () => {
  return useContext(CartContext);
}

export { CartProvider, useCartContext };
kq0g1dla

kq0g1dla1#

首先,这个if (localCartData === [])永远不会为真。我想你想检查一下存储器中是否没有东西,如果是的话,应该是if (!localCartData)
然后,由于useEffect有一个空的依赖数组,它将只在挂载时运行一次。你需要添加state作为依赖项:

useEffect(() => { 
  console.log("It Should run here")
  localStorage.setItem('CartItems', JSON.stringify(state.cart));   
}, [state])

相关问题