如何获取React Native图像失败错误代码

问题描述 投票:0回答:1

如果加载图像失败,则会调用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>
    );
  }
}

reactjs react-native react-native-android react-native-ios react-image
1个回答
0
投票

简单的解决方案(但很糟糕):

您可以获得错误消息,并检查字符串是否包含状态码,例如:

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。

我发现了一些有用的链接,如果您需要:

React-Native check image url

Fetch: reject promise and catch the error if status is not OK?

© www.soinside.com 2019 - 2024. All rights reserved.