【发布时间】: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