如何在React中应用无限滚动

时间:2018-08-12 06:23:45

标签: javascript reactjs infinite-scroll

我尝试修复我的代码,但仍然无法正常工作:( 我正在尝试进行无限滚动并使用React-Waypoint。我想无限展示{this._renderList()}。但是它仍然没有用。我正在使用YTS API,并且似乎具有页面和限制参数...你们对如何无限显示数据有想法吗?

这是yts API https://yts.am/api#list_movies

的链接
 import React, { Component } from 'react';
    import L_MovieList from './L_MovieList';
    import L_Ranking from './L_Ranking';
    //import './L_MovieList.css';
    //import './L_Left_Ranking.css';
    import './L_Right_List.css';
    class L_BoxOffice extends Component {
  state ={

  };


  constructor(props) {
      super(props);
      this.state = {movies:[]}
      this._renderRankings = this._renderRankings.bind(this);
      this._renderList = this._renderList.bind(this);
      this.handleOnScroll = this.handleOnScroll.bind(this);
  }
  componentDidMount(){
    if(this.state.newData.length === 0){
      window.addEventListener('scroll', this.handleOnScroll);
      this.doQuery(1).then(res=>
        this.setState({
         newData: this.state.newData.slice().concat(res),
        requestSent: false
      }))
    }
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleOnScroll);
  }

  handleOnScroll(){
    var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
    var clientHeight = document.documentElement.clientHeight || window.innerHeight;
    var scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight;
    if (scrolledToBottom) {
      this.setState({
        scrollCounter: this.state.scrollCounter + Math.floor(scrolledToBottom)
      },()=>{
              if(this.state.scrollCounter<4){
        this.doQuery(this.state.scrollCounter).then(res=>
        (res===BUSY)
          ? false
          : this.setState({
              newData: this.state.newData.slice().concat(res)
            })
          )
          .catch(err=>this.setState({requestSent: false}))
          this.setState({requestSent: true});
      }else{
        return true
      }
   })
    }
  }
componentWillMount(){
    this._getMovies();
}
_renderRankings=()=>{
  const movies= this.state.movies.map((movie, i)=>{
    console.log(movie)
      return  <L_Ranking
      title={movie.title_english}
      key={movie.id}
      genres={movie.genres}
      index={i}
      />
  })
  return movies
}
_renderList=()=>{
  const movies= this.state.movies.map((movie)=>{
    console.log(movie)
      return  <L_MovieList
        title={movie.title_english}
        poster={movie.medium_cover_image}
        key={movie.id}
        genres={movie.genres}
        language={movie.language}
        runtime={movie.runtime}
        year={movie.year}
        rating={movie.rating}
        likes={movie.likes}
        trcode={movie.yt_trailer_code}


      />
  })
  return movies
}
_getMovies = async()=>{
  //async는 이전의 작업이 끝날때까지 기다리는 것이 아닐때. 이전작업이 끝나야 그 다음 작업이 시작하는 형태가 아니다
 const movies = await this._callApi() //_callApi가 끝나는걸 기다린다. 성공적인 수행이 아닌.
 this.setState({//_callApi가 끝나야 실행된다
   //movies : movies
   movies //_callApi의 리턴밸류(json.data.movies)를 movies에 넣는다
 })
}
  _callApi=()=>{
    return   fetch('https://yts.am/api/v2/list_movies.json?sort_by=download_count&limit=2')
    .then(potato=> potato.json()) //response오브젝트를 우리가 볼수 있는 json으로 바꿔줘야한다.
  //  .then(jason=> console.log(json))
    .then(json=> json.data.movies)
    //fetch가 끝나면, 성공적 수행이 아니라 그냥 작업이 완료되면 then을 부른다
  //then 펑션은 1개의 어트리뷰트만 반환한다.그것은 오브젝트이다 =패치의 결과
  //=> ()애로우평션)에서는 return작성없이 자동으로 해준다.
    .catch(err=>console.log(err))
    //fetch가 끝난후 뭔가 해라(then) 근데 위의 라인에 에러가있으면(fetch)에서?
    // catch 잡아서 나한테 보여//
    }
  render() {
    const{movies}=this.state;
   let sub_title;
   let right_information;
   if( this.props.page == 'main')
   {
     sub_title = <div>Today Box Office</div>;
     right_information= <div> aaa</div>;
   }
   else if( this.props.page == 'box_office' )
   {
     right_information = <div className={movies ? "L_Right_List" : "L_Right_List--loading"}>
 {this._renderList() }

       </div>;
   }
    return (
      <div style={{backgroundColor:'#E5E5E5', paddingTop:'20px', paddingLeft:'20px'}}>
{sub_title}
      <div className={movies ? "L_Left_Ranking" : "L_Left_Ranking--loading"}>
      <div className="L_Left_Ranking_title">영화랭킹</div>
{this._renderRankings() }
      </div>
     {right_information}


      </div>
    );
  }
}

export default L_BoxOffice;

0 个答案:

没有答案