如果加载图像失败,则会调用onError
方法。但是,它没有告诉我们失败的原因。有没有办法找出为什么RN无法加载图像?是因为404还是500,还是用户未连接到互联网?等
import React, { Component } from 'react';
import { View, Image } from 'react-native';
export default class DisplayAnImage extends Component {
render() {
return (
<View>
<Image
style={{width: 50, height: 50}}
onError={({ nativeEvent: {error} }) => {
console.log(error) // < ---- How to get error code?
}
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
/>
</View>
);
}
}
简单的解决方案(但很糟糕):
您可以获得错误消息,并检查字符串是否包含状态码,例如:
const errorMessage = "Failed to load resource https://reactnative.dev/img/random_image.png (404)"
errorMessage.includes("404")
另一个解决方案
使用获取。
fetch("https://reactnative.dev/img/random_image.png")
.then((res) => {
// the request status in in res.status
// res.status = 404 -> error
// res.status = 200 -> success
})
.catch((e) => {})
仅在发生网络错误时,获取承诺才会拒绝,并返回TypeError。
我发现了一些有用的链接,如果您需要:
Fetch: reject promise and catch the error if status is not OK?