首页 > 解决方案 > 如何在 MERN 堆栈应用程序中使异步/等待功能直到状态更新

问题描述

我想让我的函数等待chosenImage状态更新。我可以在函数外的console.log中看到更新的状态addToCart,但是里面的console.log返回空字符串。我怎样才能让它等待状态更新?

这就是我的意思:

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

  console.log(chosenImage)

  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))
}

标签: reactjs

解决方案


为了等待状态更新然后执行 then 函数,您需要使用useEffectwith state 作为依赖

...
useEffect(()=>{
   addToCart(user, product)
},[chosenImage])

推荐阅读