【问题标题】:How to make function await till state update in MERN Stack Application [duplicate]如何在 MERN 堆栈应用程序中使函数等待状态更新 [重复]
【发布时间】:2021-06-10 19:15:16
【问题描述】:

如何让我的函数addToCart 等到chosenImage 状态更新?在第一个退出函数的console.log中,我可以看到更新的状态,但是里面的console.log返回的是空字符串。

注意:addToCart函数和状态与更新状态的按钮不在同一目录。

    const [chosenImage, setChosenImage] = useState('');
        
    console.log(chosenImage)
        
     useEffect(() => {
    
    function addToCart(user, product) {

        const cartProduct = {
            _id: product._id,
            name: product.name,
            description: product.description,
            processor: product.processor,
            ram: product.ram,
            storage: product.storage,
            price: product.price,
            type: product.type,
            likes: product.likes,
            colors: product.colors,
            images: chosenImage
        }

        fetch(`${API}/cart/usercart`, {
            method:"POST",
            headers: { 
                'Content-Type': 'application/json'
            },
        body: JSON.stringify([user._id, cartProduct])
        })
        .then(response => response.json())
        .then(response => {
            const updatedCart = response.cart;
            setUser(oldState => ({...oldState, cart: [updatedCart]}))
            localStorage.setItem("cart", JSON.stringify(updatedCart))
        })
        .catch(error => console.log(error)) 
    }
}, [chosenImage])

【问题讨论】:

  • React 状态更新是异步的,但是状态更新函数是完全同步的,不能等待。通常,您使用useEffect 在下一个渲染周期发布带有更新状态的副作用。
  • 那我怎样才能让它工作呢?
  • 所选图像在操作中更新的位置在哪里?如果添加到购物车操作依赖于所选择的正在更新的图像,请使用具有适当依赖关系的 useEffect 挂钩。
  • 我明白了。但是在 useEffect 中我无法创建函数。我试了一下,它不接受(user, product),也不接受{}
  • 当然可以做一个函数。什么是{},什么不接受?

标签: node.js reactjs mongodb express mern


【解决方案1】:

使用 useEffect 挂钩。

useEffect (()=> addToCart(user, product); ,[选择图像]);

【讨论】:

  • 我尝试过,但在 useEffect 中我无法通过(用户、产品)。我也不能像addToCart(user, product) {}这样在里面创建一个函数,它不接受{}
猜你喜欢
  • 2021-08-27
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多