我如何确保从flickr API获得不同的结果

时间:2019-05-07 11:32:29

标签: reactjs api flicker

我有一个简单的Gallery App,我想实现无限滚动,并在事件发生时渲染新图像。

我确实设法实现了滚动事件,问题是因为我正在通过用户输入进行搜索,所以得到的结果总是与当前渲染的图像数组相同。

class Gallery extends React.Component {
constructor(props) {  
    super(props);
    this.state = {
      images: [],
      galleryWidth:window.clientWidth, 
      countCloned: 1,
      scroll:false
    };

//first call when the page is render
getImages(tag) {
    const getImagesUrl = `services/rest/?method=flickr.photos.search&api_key=522c1f9009ca3609bcbaf08545f067ad&tags=${tag}&tag_mode=any&per_page=100&format=json&safe_search=1&nojsoncallback=1`;
    const baseUrl = 'https://api.flickr.com/';
    axios({
      url: getImagesUrl,
      baseURL: baseUrl,
      method: 'GET'
    })
      .then(res => res.data)
      .then(res => {
        if (
          res &&
          res.photos &&
          res.photos.photo &&
          res.photos.photo.length > 0
        ) {
          this.setState({images: res.photos.photo});
        }
      });
render() {
    return (
      <div className="gallery-root"  
           id = "gallery-id"
           ref = "iScroll"
           >
        {this.state.images.map(dto => {
          return <Image 
                  key={'image-' + dto.id} 
                  dto={dto}
                  galleryWidth={this.state.galleryWidth}
                  callBack = {this.cloneHandler.bind(this)}
                  displayImage = {this.renderImage.bind(this)}/>;
        })}
      </div>
    );
  }
}
  }

//gets called on scroll event 
getNewResults(tag){
    const getImagesUrl = `services/rest/?method=flickr.photos.search&api_key=522c1f9009ca3609bcbaf08545f067ad&tags=${tag}&tag_mode=any&per_page=200&format=json&safe_search=1&nojsoncallback=1`;
    console.log("before push " + this.state.images.length);
    const baseUrl = 'https://api.flickr.com/';
    axios({
      url: getImagesUrl,
      baseURL: baseUrl,
      method: 'GET'
    })
      .then(res => res.data)
      .then(res => {
          const oldImages = this.state.images;
          console.log(oldImages.length); //100
          const newImages = res.photos.photo;
          const allImages = oldImages.concat(newImages);
          console.log(allImages.length) // 300 (i changed the result im getting to 200 )
          this.setState({images:allImages});
         {         
        }
      });
       console.log("after push" + this.state.images.length);
  }

我可以看到每次滚动时数组的大小都变大,但是我得到了:

flattenChildren(...): Encountered two children with the same key,

因为图像相同。 如何按页面搜索闪烁?还是应该增加结果并进行过滤? 最好的解决方案是什么?

0 个答案:

没有答案