context/cart.jsx个
import { useState, useContext, createContext, useEffect } from "react";
const CartContext = createContext()
const CartProvider = ({ children }) => {
const [cart,setCart] = useState([])
const cartTotal = cart.reduce((total, item) => total + item.quantity, 0)
useEffect(() => {
let existingCartItems = localStorage.getItem("cart")
if(existingCartItems) setCart(JSON.parse(existingCartItems))
}, [])
console.log(cartTotal)
return (
<CartContext.Provider value={[cart, setCart, cartTotal]}>
{children}
</CartContext.Provider>
)
}
const useCart = () => useContext(CartContext)
export { useCart, CartProvider }
components/Header.jsx个
const Header = () => {
const [auth, setAuth] = useAuth()
const [cart, cartTotal] = useCart()
const categories = useCategory()
console.log(cartTotal)
}
我正在try 将变量cartTotal
传递给标题并显示在页面上.虽然上下文可以打印值cartTotal
,但当我try 在Header组件上打印输出时,它显示错误function dispatchSetState(fiber, queue, action) { { if (typeof arguments[3] === 'function') { error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); } }
,因此有人可以帮助找出一些解决方案吗?