动态更改惊奇API偏移量

时间:2019-02-07 01:19:31

标签: javascript reactjs api

我正在使用惊奇的API,我想在正在构建的应用程序中设置无限滚动功能。一切都按照我想要的方式进行,直到达到一定数量的字符为止。

我想加载更多字符,但是在某个时候,出现控制台错误,提示结果未定义。我想我需要调整偏移量,以便它将加载更多字符。但是我该如何动态地执行此操作,以使我的无限滚动功能正常工作并最终加载所有字符?

class CharacterList extends Component {
  state = {
    characters: [],
    limit: 20,
    offset: 0,
  }

  async componentDidMount() {
    window.addEventListener('scroll', this.onScroll, false);
    try {
      // fetch initial list with default limit of 20
      const res = await fetch(`https://gateway.marvel.com:443/v1/public/characters?limit=${this.state.limit}&offset=${this.state.offset}&apikey=66ef26227cbc5462b13d6310153279e2`);
      const characters = await res.json();
      this.setState({
        characters: characters.data.results,
      });
    } catch (e) {
      console.log(e);
    }
  }

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

  // increment the limit and offset of comics by 20
  incrementLimit = async () => {
    try {
      const nextNum = this.state.limit + 20;
      const nextOffset = this.state.limit + 20;
      const res = await fetch(`https://gateway.marvel.com:443/v1/public/characters?limit=${nextNum}&offset=${nextOffset}&apikey=66ef26227cbc5462b13d6310153279e2`);
      const characters = await res.json();
      this.setState({
        limit: this.state.limit + 16,
        characters: [...characters.data.results],
      });
    } catch (e) {
      console.log(e);
    }
  };

  onScroll = () => {
    if (
      (window.innerHeight + window.scrollY) >= (document.body.offsetHeight)
      && this.state.characters.length
    ) { this.incrementLimit(); }
  }

  addOffset = () => {
    this.setState((prevState) => {
      const nextOffset = prevState.limit > 90 ? this.state.limit = prevState.limit + 20 ? prevState.offset + 20 : this.state.offset = prevState.offset : this.state.offset = prevState.offset;
    });
  }

  render() {
    if (typeof this.state.characters === 'undefined') {
      return (
        <LinearProgress />
      );
    }
    return (
      <CharContainer>
        <CharacterGrid>
          {this.state.characters
            .filter(character => character.thumbnail.path !== 'http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available')
            .map(character => <Character key={character.id} character={character} />,
            )
          }
        </CharacterGrid>
      </CharContainer>
    );
  }
}


export default CharacterList;

0 个答案:

没有答案