React Native如何在错误时替换图片URL?

时间:2019-04-17 07:24:04

标签: react-native react-native-android react-native-image

我有一个应用程序,可以显示我从API加载的多个图像。现在的问题是某些图像已过期,这在Android上引起了问题,在Android中,一旦过期的图像加载到屏幕上,屏幕就会开始滞后。

我尝试用onError={() => this.imgRefs[img_unique_id].setNativeProps({src: [{uri: this.state.workingUri}]})}替换图像源,但是这种方法不起作用。 我无法使用本地状态,因为它没有将输出保存为本地状态。

我尝试了以下代码

  <Image  
      source={image.url} 
      progressiveRenderingEnabled={true}
      ref={item.id} 
      onError={(e) => this.refs[item.id].setNativeProps({source: [{uri: "working image URL"}]})} 
      resizeMethod={"scale"}>
   </Image>      

上面的代码给了我一个未定义的setNativeProps错误,如果我不在android上使用onError,它将向我显示内存泄漏错误。

2 个答案:

答案 0 :(得分:0)

我认为您应该使用从Api接收的数据并在componentWillReceiveProps内相应地设置状态,因为我认为设置状态是实现此结果的最佳方法。  

 this.setState = { image: { uri: 'image_uri_from_api' } }

<Image>内添加-

 <Image style={ your_custom_style }
       source={ this.state.image }
       onError={ this.onError.bind(this) }
 />

onError内添加此内容-

onError(error){
   this.setState({ image: require('your_local_image.path')})
 }

希望它现在可以工作!

答案 1 :(得分:0)

这是一个完整的例子。为了使每个FlatList项目都有自己的状态,我创建了一个类。

import React, { Component, PureComponent } from 'react';
import { FlatList, Text, View, Image } from 'react-native';

class ItemClass extends PureComponent {
  state = {
    isImageExit: null
  }
  componentWillMount = () => {
    const { task } = this.props;
    Image.getSize(task.url, (width, height) => {
        if(width>0){
            this.setState({ isImageExit: true });
        }
        else{
            this.setState({ isImageExit: false });
        }
    }, () => {
      this.setState({ isImageExit: false });
    });
  }

  render() {
    const { isImageExit } = this.state;
    const { task } = this.props;
    const url = isImageExit ? task.url : 'https://dummyimage.com/600x400/000/fff';
    if (isImageExit === null) {
      return null;
    }
    return (
      <Image
        style={{ height: 200, width: 200 }}
        source={{ uri: url }}
      />
    );
  }
}

export default class App extends Component {
  render() {
    const data = [
      { url: 'url' },
      { url:'https://cdn.pixabay.com/photo/2017/08/05/18/53/mountain-2585069_1280.jpg' },
    ];
    return (
      <View style={{alignItems: 'center', top: 50}}>
          <FlatList
            data={data}
            renderItem={({ item }) => <ItemClass task={item} />}
          />
      </View>
    );
  }
}