On Each refresh
of page, due to this stateAssignment
const [cart, setCart] = useState({cartItems: []});
This useEffect
is executed.
useEffect(() => {
localStorage.setItem("cartItems", JSON.stringify(cart.cartItems));
}, [cart.cartItems])
And at that time cart.cartItems
is []
. Hence it is set to []
.
You need to make sure that this useEffect
should only run when there is a user-initiated change in cart.cartItems
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…