首页 > 解决方案 > 相机胶卷功能获取重复图像

问题描述

我正在使用相机胶卷进行本机反应以在我的移动设备上获取图像,我使用first: 1,在相机胶卷功能运行后,它存储end_cursor来自数据并在后续的相机胶卷请求中使用它作为后变量,即

 CameraRoll.getPhotos({
       first: 1,
       assetType: 'Photos',
       after: end_cursor
     })

然后,当平面列表的末尾也得到时,我运行一个函数,以根据end_cursor变量加载更多图像。图像不断出现两次,状态中有重复的图像,即 [图像 1,图像 1,图像 2,图像 2,....],可能导致此错误的原因,这是我下面的完整代码

constructor(props) {
    super(props);
    this.state = {
      photos: [],
      lastCursor: null,
      noMorePhotos: false,
      loadingMore: false,
    };
  }
  tryPhotoLoad() {
    if (!this.state.loadingMore) {
      this.setState({ loadingMore: true }, () => { this.loadPhotos(); });
    }
  }

  loadPhotos() {
    const fetchParams = {
      first: 1,
      assetType: 'Photos',
    };
    if (this.state.lastCursor) {
     // console.log("last cursor "+this.state.lastCursor)
      fetchParams.after = this.state.lastCursor;
    }

    CameraRoll.getPhotos(fetchParams).then((data) => {
      this.appendAssets(data);
    }).catch((e) => {
    //  console.log(JSON.stringify(e));
    });
  }

  appendAssets(data) {
    console.log("\n"+"\n"+"\n"+JSON.stringify(data)+"\n"+"\n"+"\n")
    const assets = data.edges;
    const nextState = {
      loadingMore: false,
    };

    if (!data.page_info.has_next_page) {
      nextState.noMorePhotos = true;
    }

    if (assets.length > 0) {
      this.setState({lastCursor: data.page_info.end_cursor})
   //   nextState.lastCursor = data.page_info.end_cursor;
      let len = assets.length;
     // console.log(len);
      for (let i = 0; i < len; i++) {
        let row = assets[i];
      //  console.log(row);
        this.setState(prevState => ({
          photos: [...prevState.photos, row]
        }));
      }
    }
   //  console.log("\n"+"\n"+"\n"+JSON.stringify(nextState)+"\n"+"\n"+"\n");
    this.setState(nextState);
  }

  endReached() {
    if (!this.state.noMorePhotos) {
      this.tryPhotoLoad();
    }
  }
  componentDidMount(){
    this.tryPhotoLoad();
  }

  render() {
    const images =(
      <FlatList
        data={this.state.photos}
        numColumns={4}
        renderItem={({ item, index }) => (
          <View style={{width: '25%',
             height: height}}>
          <Image
           key={index}
           resizeMode={'cover'}
           style={{
             flex: 1
           }}
           source={{ uri: item.node.image.uri }}
         /></View>
        )}
        keyExtractor={(item, index) => `list-item-${index}`}
        onEndReached={this.endReached()}
        onEndReachedThreshold={0}
       />
    );
    return (
      <View
        style={{ flex: 1, backgroundColor: "#DDDBC7", flexDirection: "column" }}
      >
 <ScrollView>
         {images}
        </ScrollView>
 );
  }

标签: javascriptreactjsreact-nativestate

解决方案


推荐阅读