1

如果加载图像失败,则onError调用方法。但是它并没有告诉我们失败的原因。有没有办法找出为什么 RN 无法加载图像?是因为 404 或 500 还是用户没有连接到互联网?ETC

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>
    );
  }
}

4

1 回答 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) => {})

Fetch Promise 仅在发生网络错误时以 TypeError 拒绝。

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

React-Native 检查图片 url

获取:如果状态不正常,拒绝承诺并捕获错误?

于 2020-03-25T01:55:11.040 回答