0

我有一个应用程序,它显示了我从 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,它会显示内存泄漏错误。

4

2 回答 2

4

这是一个完整的例子。为了让每个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>
    );
  }
}
于 2019-04-17T12:23:48.683 回答
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')})
 }

希望它现在有效!

于 2019-04-17T07:49:26.483 回答