使用钩子 useState() 的问题

简单样本

尝试使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章