【发布时间】:2021-08-27 14:22:41
【问题描述】:
我想让我的函数等待chosenImage 状态更新。我可以在addToCart 函数中看到console.log 中的更新状态,但是里面的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))
}
【问题讨论】:
-
我没有看到你打电话给
setChosenImage。或者您想致电addToCard何时chosenImage更新? -
是的,当 selectedImage 更新时调用 addToCard
标签: reactjs