lay*_*thq 2 javascript reactjs react-hooks
我正在使用 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 (...)
}
Run Code Online (Sandbox Code Playgroud)
我已经将照片道具传递到我的 useEffect 钩子的依赖数组中,所以它应该在照片道具改变时触发。我可以看到 prop 确实在控制台中发生了变化,但是当 prop 发生变化时,我的 useEffect 钩子没有触发。这是出现在我的控制台中的内容:
为什么 useEffect 没有触发两次?根据我的理解,它应该在组件第一次渲染时触发,并在每次photosprop 更改时再次触发。
| 归档时间: |
|
| 查看次数: |
4934 次 |
| 最近记录: |