reactjs - 如何在 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))
}
解决方案
为了等待状态更新然后执行 then 函数,您需要使用useEffect
with state 作为依赖
...
useEffect(()=>{
addToCart(user, product)
},[chosenImage])
推荐阅读
- android - 为什么创建的Activity背景是透明的?
- dreamfactory - Dreamfactory - 为什么我的服务器事件脚本没有被调用?
- java - javax验证:将多个注释分组在同一个组上
- java - CrudRepository 不会删除有关系的对象
- jquery - Jquery tagsinput自动完成在引导模式下不起作用
- r - 使用 NLMR 包修复 R 中的种子
- java - Spring - LDAP 身份验证 - CRYPT-MD5 密码的密码编码器
- mysql - MySQL - 选择过去十条记录进行列组合
- android - 如何从从 recyclerView 启动的对话框中获取片段
- angular - providedIn: 'root' 自动声明服务进行测试