如果 url 显示加载错误,如何再次重新加载图像 url

发布于 2025-01-11 07:54:36 字数 2626 浏览 0 评论 0原文

我正在尝试使用图像组件从 Flatlist 上的 URL 加载图像。在此组件中,有一个属性 (onError?: () => void ) 该属性在图像获取错误时被调用。 当我在低网络中运行我的应用程序时,一些图像无法加载,所以我应该在 (onError?: () => void ) 中编写什么代码,以便无法加载图像的 URL 在低网络中再次加载一次。

我正在 React Native for iOS 中创建这个应用程序,

我已经这样做了:

App.js

import React, { useState } from 'react';
import Product from './product';
import {
  FlatList,
  SafeAreaView
} from 'react-native';

const products = [
  {productImage: "https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612"},
  {productImage: 'https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612'},
  {productImage: "https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612"},
  {productImage: 'https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612'},
]

const App = () => {
  return (
    <SafeAreaView>
      <FlatList 
      numColumns={2}
      data={products}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item }) => (<Product product={item} />)}>
</FlatList>
    </SafeAreaView>
  );
};

export default App;

Product.js

import React from 'react';
import { View, Image } from 'react-native';

class Product extends React.Component {

    constructor(props){
     super(props);
     this.state = {
       uri : this.props.product.productImage,
       errorCount : 0
     }
    }

    passInError(e) {
      const { productImage } = this.props.product
          if (this.state.errorCount < 3) {
            this.setState({uri: productImage, errorCount: ++this.state.errorCount})
            console.log(" Corrupt Image URL : " + productImage )
            console.log(" Corrupt Image Error Reason : ", JSON.stringify(e) )
            console.log (" Corrupt Image Reload Count : ", this.state.errorCount)
          }
        }

    render() {
        return (
            <View>
              <Image
                 style={{ width: 200, height: 200, borderWidth: 2, }}
                 source={{ uri:this.state.uri }}
                 onError = {e => this.passInError(e.nativeEvent) }
                 key = {this.state.errorCount}
              />
            </View>
        )
    }
}

export default Product;

我应该在 (onError?: () => void ) 函数中编写什么代码来重新加载失败的图像 URL?

I am trying to load images from URL on flatlist using Image Component. In this component there is a property (onError?: () => void ) this property is called on an image fetching error.
When I run my app in low network some images failed to load, so what code should I write in (onError?: () => void ) so that the URL that failed to load images should load one more time in low network.

I am creating this App in React Native for iOS

I have done this :

App.js

import React, { useState } from 'react';
import Product from './product';
import {
  FlatList,
  SafeAreaView
} from 'react-native';

const products = [
  {productImage: "https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612"},
  {productImage: 'https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612'},
  {productImage: "https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612"},
  {productImage: 'https://media.istockphoto.com/photos/poverty-concept-used-red-shoes-for-children-in-a-thrift-shop-between-picture-id1303292803?s=612x612'},
]

const App = () => {
  return (
    <SafeAreaView>
      <FlatList 
      numColumns={2}
      data={products}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item }) => (<Product product={item} />)}>
</FlatList>
    </SafeAreaView>
  );
};

export default App;

product.js

import React from 'react';
import { View, Image } from 'react-native';

class Product extends React.Component {

    constructor(props){
     super(props);
     this.state = {
       uri : this.props.product.productImage,
       errorCount : 0
     }
    }

    passInError(e) {
      const { productImage } = this.props.product
          if (this.state.errorCount < 3) {
            this.setState({uri: productImage, errorCount: ++this.state.errorCount})
            console.log(" Corrupt Image URL : " + productImage )
            console.log(" Corrupt Image Error Reason : ", JSON.stringify(e) )
            console.log (" Corrupt Image Reload Count : ", this.state.errorCount)
          }
        }

    render() {
        return (
            <View>
              <Image
                 style={{ width: 200, height: 200, borderWidth: 2, }}
                 source={{ uri:this.state.uri }}
                 onError = {e => this.passInError(e.nativeEvent) }
                 key = {this.state.errorCount}
              />
            </View>
        )
    }
}

export default Product;

What code should I write in (onError?: () => void ) function to reload failed images URL ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不知在何时 2025-01-18 07:54:36

尝试在状态中设置图像 url,并在加载图像时出错时更新。

product.js

import React from 'react';
import { View } from 'react-native';
import FastImage from 'react-native-fast-image';

class Product extends React.Component {
    constructor(props){
     super(props);
     this.state = {
       uri : this.props.product.productImage,
       errorCount : 0
     }
    }

    render() {
        const { productImage } = this.props.product
        return (
            <View>
              <FastImage
                 style={{ width: 200, height: 200, borderWidth: 2, }}
                 source={{ uri:this.state.uri }}
                 resizeMode={FastImage.resizeMode.contain}
                 onError={e =>
                   this.state.errorCount < 3 &&
                   this.setState(
                     {uri: '', errorCount: ++this.state.errorCount},
                       () => this.setState({uri: productImage}),
                   )
                 }
              />
            </View>
        )
    }
}

export default Product;

Try setting image url in state and update when error on loading image.

product.js

import React from 'react';
import { View } from 'react-native';
import FastImage from 'react-native-fast-image';

class Product extends React.Component {
    constructor(props){
     super(props);
     this.state = {
       uri : this.props.product.productImage,
       errorCount : 0
     }
    }

    render() {
        const { productImage } = this.props.product
        return (
            <View>
              <FastImage
                 style={{ width: 200, height: 200, borderWidth: 2, }}
                 source={{ uri:this.state.uri }}
                 resizeMode={FastImage.resizeMode.contain}
                 onError={e =>
                   this.state.errorCount < 3 &&
                   this.setState(
                     {uri: '', errorCount: ++this.state.errorCount},
                       () => this.setState({uri: productImage}),
                   )
                 }
              />
            </View>
        )
    }
}

export default Product;
另类 2025-01-18 07:54:36

如果我理解正确的话,当第一次尝试出现错误时,您想尝试第二次加载相同的图像。我会尝试在错误时重新渲染组件(更好的是,用包装器组件包装图像组件,这样整个产品组件就不会重新渲染):

const Product = () => {
  const [fetchCounter, setFetchCounter] = useState(0);

  return (
    <img 
      src={'imageUrl'}
      onError={() => {
        if (fetchCounter < 1) {
          setFetchCounter(fetchCounter++);
        }
      }} 
    />
  )
}

我不知道您的用例,但您可以加载后备图像代替。它可能看起来像这样:

const Product = () => {
  const [imageUrl, setImageUrl] = useState('product-img-url');

  return (
    <img 
      src={imageUrl}
      onError={() => setImageUrl('fallback-img-url')} 
    />
  )
}

If I understand you correctly, you want to try to load the same image for a 2nd time when there is an error on the 1st try. I would try to re-render the component on Error (even better, wrap the image component with a wrapper component so that the whole Product component is not re-rendered):

const Product = () => {
  const [fetchCounter, setFetchCounter] = useState(0);

  return (
    <img 
      src={'imageUrl'}
      onError={() => {
        if (fetchCounter < 1) {
          setFetchCounter(fetchCounter++);
        }
      }} 
    />
  )
}

I do not know your use case, but you can load a fallback image instead. It could look something like this:

const Product = () => {
  const [imageUrl, setImageUrl] = useState('product-img-url');

  return (
    <img 
      src={imageUrl}
      onError={() => setImageUrl('fallback-img-url')} 
    />
  )
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文