如何在 MERN 堆栈应用程序中使用 Hooks 更新 Context 中的状态

How to update state in Context using Hooks in MERN Stack Application

我正在尝试找到一种方法来更新我的“用户”状态,但我已经被困在这里 3 天了,我需要一些帮助。

这是我的用户上下文:

import React, {useEffect, useState} from 'react';

export const UserContext = React.createContext({})
const UserProvider = UserContext.Provider;

const UserContextProvider = (props) => {
    const [user, setUser] = useState({})
    
    useEffect(() => {
        fetch(`${API}/auth/user`, {
            method: 'GET',
            withCredentials: true,
            credentials: 'include'
        })
        .then (response => response.json())
        .then (response => {
            setUser(response.user)
        })
        .catch (error => {
            console.error (error);
        });
    }, [setUser])

    console.log(user)

    return (
        <UserProvider value={{user, setUser}}>
            {props.children}
        </UserProvider>
    )
}   

export default UserContextProvider;

这是我尝试更新用户的地方。在我的例子中,我试图在 user.cart 数组中推送一个对象,因为后端的一切都很好,但在前端状态没有更新:

然后在这里我尝试更新用户状态,但是当我点击按钮时它让我注销了:

<button className="addTo--Cart--Button--Container">
      <FaShoppingCart onClick={() => {addToCart(user._id, product); setUser(oldState => oldState.cart.push(product))}}/>
</button>

注销后,UserContextProvider 函数中的 console.log(user) 仅记录 user.cart 更新的长度。

还有一个:

如何从上下文中删除项目:

这是我的删除函数:

const removeFromContextCart = (id) => {
        console.log(id)
        const updatedCart = user.cart.filter((item) => item.id !== id);
        setUser(oldState => ({
            ...oldState,
            cart: [
                ...oldState.cart,
                updatedCart
            ]
        }))
    }

还有我的按钮:

<button className="remove--Button" onClick={() => {removeFromCart(user._id, product); setUser(removeFromContextCart(product._id))}}> REMOVE</button>

尝试用这种方式更新用户状态

setUser(oldState => ({
  ...oldState,
  cart: [
    ...oldState.cart,
    product
  ]
}))