【发布时间】:2020-06-03 09:41:32
【问题描述】:
我正在使用 useEffect 挂钩根据传入的 photos 道具中的数据进行 API 调用。
const ImageCarousel = ({ src, photos }) => {
const [photoList, setPhotos] = useState([]);
const storageRef = firebase.storage().ref();
console.log("photos prop:", photos);
const getImage = photoId => {
return new Promise((resolve, reject) => {
storageRef
.child("images/" + photoId)
.getDownloadURL()
.then(url => resolve(url))
.catch(error => reject(error));
});
};
useEffect(() => {
console.log("trigger");
Promise.all(
photos.map(async photoId => {
const url = await getImage(photoId);
return url;
})
)
.then(photoUrls => {
setPhotos(photoUrls);
})
.catch(e => console.log(e));
}, [photos]);
return (...)
}
我已将照片道具传递到我的 useEffect 钩子的依赖数组中,因此当照片道具更改时它应该会触发。我可以看到控制台中的道具确实发生了变化,但是当道具更改通过时,我的 useEffect 钩子不会触发。这是我的控制台中显示的内容:
为什么 useEffect 没有触发两次?据我了解,它应该在组件第一次渲染时触发,并在每次 photos 属性更改时再次触发。
【问题讨论】:
-
您是否尝试将不同的照片道具值传递给组件并检查是否触发了
useEffect?useEffect只会在新值与旧值不同时触发。 -
是的,已经尝试使用不同的道具而不是传递一个空数组,但它仍然没有触发
useEffect。 -
根据控制台屏幕截图,我觉得您将相同的值传递给道具,这就是为什么我这样通知的原因,如果您添加了传递道具,那么检查确切的问题会很好
标签: javascript reactjs react-hooks