如何从Firebase Storage下载图片并在React Native地图Marker中显示
如何将Firebase Storage下载的图片显示在MapView Marker的Image组件中
我已经实现了从Firebase Storage获取图片下载URL的函数,现在需要把这个URL对应的图片设置到Main组件中MapView Marker的Image组件里,作为标记图标。
获取图片的函数代码
export const getMyImage = async (userId) => { try { if (!userId) { throw new Error("Invalid userId"); } // 获取存储引用 const userDocRef = ref(storage, `${userId}/image`); // 获取图片的下载URL const downloadURL = await getDownloadURL(userDocRef); console.log("TEST", downloadURL); // 这段XHR代码无实际作用,可移除 const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = (event) => { const blob = xhr.response; }; xhr.open('GET', downloadURL); xhr.send() // 返回URL return downloadURL; } catch (error) { console.error("getMyImage: ", error); throw error; } };
目前已经能获取到有效的下载URL(类似https://xxx.xxx.xxx/image.png格式),但无法直接在Marker的Image组件中显示。
Main组件相关代码片段
我在Main组件中定义了iconImage状态,并在useEffect中调用getMyImage获取URL后更新状态,但图片未正常显示:
const Main = () => { // ...其他状态定义 const [iconImage, setImageUri] = useState(null); useEffect(() => { // ...其他逻辑 const fetchData = async () => { try { const fetchMyImage = await getMyImage(user_id); console.log("fetchMyImage", fetchMyImage); setImageUri(fetchMyImage); } catch (error) { console.error("Error fetching image: ", error); } }; fetchData(); // ...其他逻辑 }, []); // ...返回JSX部分 return ( // ...省略其他代码 <Marker coordinate={{ latitude: myCurrentLocation.latitude, longitude: myCurrentLocation.longitude, }}> <Image style={styles.icon} source={iconImage} /> </Marker> // ...省略其他代码 ); };
解决方案
问题出在React Native的Image组件对网络图片的处理规则:直接传入URL字符串无效,必须包装成{ uri: 下载URL }的对象格式。
具体修复步骤:
- 修改状态赋值方式
在fetchData中调用setImageUri时,传入包含uri字段的对象:
setImageUri({ uri: fetchMyImage });
- 简化
getMyImage函数
移除无实际作用的XHR下载代码:
export const getMyImage = async (userId) => { try { if (!userId) { throw new Error("Invalid userId"); } const userDocRef = ref(storage, `${userId}/image`); const downloadURL = await getDownloadURL(userDocRef); console.log("TEST", downloadURL); return downloadURL; } catch (error) { console.error("getMyImage: ", error); throw error; } };
- 可选:添加默认图片
为避免图片加载前显示空白,可给iconImage设置本地默认资源:
const [iconImage, setImageUri] = useState(require('../../assets/default-icon.png'));
完成以上修改后,Image组件就能正确加载Firebase Storage返回的网络图片,显示在Marker上。
内容的提问来源于stack exchange,提问作者谷口祐人
相关产品推荐
相关产品推荐

