【问题标题】:react how to make a pagination in external api反应如何在外部api中进行分页
【发布时间】:2019-08-03 22:21:04
【问题描述】:

请帮助在外部 API (pokeapi.co) 中对信息结果进行分页我可以获取所有项目,我已将答案限制为 100 个单位,现在我想在每页中分十页,但有以下错误,当我单击分页链接切换页面时,项目仍然没有显示为分页。

请问,谁能帮帮我?提前谢谢你。

    import React, { Component } from 'react';
    import axios from 'axios';
    import Pagination from 'react-js-pagination';
    import PokemonCard from './PokemonCard';

    require ('bootstrap-less/bootstrap/bootstrap.less');

    export default class PolemonList extends Component {
     constructor(props) {
     super(props);
     this.state = {
      activePage: 1,
      pageNumber: 10
    };
   }

    handlePageChange(pageNumber) {
    console.log(`active page is ${pageNumber}`);
    this.setState({activePage: pageNumber});
  }

  state = {
    url: 'https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100',
    pokemon: null
  };

  async componentDidMount() {
    const res = await axios.get('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100');
    this.setState({ pokemon: res.data['results'] })
  }

  render() {
    return(
      <React.Fragment>
        {this.state.pokemon ? (
          <div className="row">
            {this.state.pokemon.map(pokemon => (
              <PokemonCard
                key={pokemon.name}
                name={pokemon.name}
                url={pokemon.url}
              />
              ))}
          </div>
        ) : (
              <h2>Loading Pokemon</h2>
        )}
        <hr></hr>
        <div className="row">
          <div className="col-12 text-center">
            <Pagination
              activePage={this.state.activePage}
              itemsCountPerPage={8}
              totalItemsCount={100}
              pageRangeDisplayed={10}
              onChange={this.handlePageChange}
            />
          </div>
        </div>
      </React.Fragment>
    );
  }
}

以下错误:

this.setState 不是我列出的代码第 21 行中的函数。

【问题讨论】:

  • 你为什么要初始化两次状态,我的意思是在构造函数中你为 activePage 和 pageNumber 初始化一个状态,而在外面你正在为 url 和 pokemon 做它,你为什么不初始化 url 以及pokemon 也在构造函数中,并试一试。如果它再次失败,我们会关注它。

标签: reactjs


【解决方案1】:

您的代码是有效的,因此您的构建/项目设置一定有错误或其他问题。

【讨论】:

  • “有效”是指不应该有“this.setState 不是我列出的代码的第 21 行中的函数”。但是,您的分页代码没有做任何事情。您的“handlePageChange”函数正在正确设置活动页面,但您还需要在该函数中加载不同的口袋妖怪并将状态设置为新的口袋妖怪组。
猜你喜欢
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 2020-10-23
  • 2016-04-09
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
相关资源
最近更新 更多