Reactjs 如何获取本机映像故障错误代码
如果加载映像失败,则调用Reactjs 如何获取本机映像故障错误代码,reactjs,react-native,react-native-android,react-native-ios,react-image,Reactjs,React Native,React Native Android,React Native Ios,React Image,如果加载映像失败,则调用onError方法。然而,它没有告诉我们失败的原因。有没有办法找出RN无法加载图像的原因?是因为404或500,还是用户没有连接到互联网?等 import React, { Component } from 'react'; import { View, Image } from 'react-native'; export default class DisplayAnImage extends Component { render() { return
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>
);
}
}
import React,{Component}来自'React';
从“react native”导入{View,Image};
导出默认类DisplayAnImage扩展组件{
render(){
返回(
{
console.log(错误)/<----如何获取错误代码?
}
source={{uri:'https://reactnative.dev/img/tiny_logo.png'}}
/>
);
}
}
简单的解决方案(但不好):
您可以获取错误消息并检查字符串是否包含状态代码,例如:
const errorMessage = "Failed to load resource https://reactnative.dev/img/random_image.png (404)"
errorMessage.includes("404")
另一种解决方案
使用Fetch
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) => {})
当发生网络错误时,Fetch承诺仅拒绝TypeError
如果您需要,我发现了一些有用的链接:
简单的解决方案(但不好):
您可以获取错误消息并检查字符串是否包含状态代码,例如:
const errorMessage = "Failed to load resource https://reactnative.dev/img/random_image.png (404)"
errorMessage.includes("404")
另一种解决方案
使用Fetch
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) => {})
当发生网络错误时,Fetch承诺仅拒绝TypeError
如果您需要,我发现了一些有用的链接:
您的第一个解决方案没有给出错误代码。它只是将失败的URL提供给我。(你觉得不同吗?)。第二种方法可行,但这意味着我将进行2次网络呼叫,这是我想要避免的。您的第一种解决方案没有给出错误代码。它只是将失败的URL提供给我。(你觉得不同吗?)。第二种方法可行,但这意味着我将拨打两个我想避免的网络电话。