尝试使用fetched data
成钩子useState(fetchedData)
const [car, setCar] = useState({images: []});
useEffect( () => {
fetchOneCar(id)
.then(data => setCar(data))
.finally(() => setLoading(false))
},[id]);
const [images,setImages] = useState(car.images)
console.log(images) // -> [] unpredictably empty
console.log(car.images) // -> [{},{},{}] (fetched data)
在我的情况下,如何正确地将数据设置为 useState() ?
好的,首先看汽车,{images:[]}
然后是图像[]
,然后汽车变成您在使用效果中获取的任何数据,仅仅因为您声明useState
使用后效果并不意味着它会在之后运行useEffect
。首先是所有的useStates
运行,然后是效果。这就是法律。所以没有意外的结果。要在您的使用效果中解决此问题,请执行以下操作:
useEffect( () => {
fetchOneCar(id)
.then(data => {
setCar(data);
setImages(data)
})
.finally(() => setLoading(false))
},[id]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句