如何实现分页在页面上显示10个对象?这是我的沙箱:
答案 0 :(得分:0)
有两种方法可以实现这一目标,
使用API的分页
使API处理某些请求参数,例如
{
**per_page_limit**: <no of record on a single page>,
**current_page**: <current page number>,
....other request param
}
客户端上的分页
获取所有记录并创建一个分页,为此获取列表的长度,并根据您的要求创建页面, 例如总记录:100 每页限制:10,因此总页数为10 现在只显示页面数据,使用setState和数据使用
list_data_to_display = list.slice(0,页面*限制)
this.setState({slow_list:list_data_to_display})
handlePageChange =(pageNumber)=> {}
解决方案将是:
this.state = {
items: [],
isLoading: false,
activePage: 1,
itemsCountPerPage: 1,
totalItemsCount: 1,
**show_list**: []
};
show_list_data = () => {
const show_list_data = this.state.items.slice(0, 10);
this.setState({
show_list: show_list_data
});
};
componentDidMount() {
fetch("https://demo9197058.mockable.io/users")
.then(res => res.json())
.then(json => {
this.setState(
{
items: json,
isLoading: true
},
this.show_list_data
);
});
}
handlePageChange = pageNumber => {
console.log(`active page is ${pageNumber}`);
const show_list_data = this.state.items.slice(
(pageNumber - 1) * 10,
pageNumber * 10
);
this.setState({
show_list: show_list_data,
activePage: pageNumber
});
};
render() {
var { show_list, isLoading } = this.state;
if (!isLoading) {
return <div> loadding....</div>;
} else {
return (
<div>
<ul>
{show_list.map(item => (
....
....
答案 1 :(得分:0)
有两件事要做:
handlePageChange
或将其转换为箭头函数items
中删除将不会显示的数据.slice(this.state.activePage * this.state.itemsCountPerPage,(this.state.activePage + 1) * this.state.itemsCountPerPage)
看看我对代码的更改:
https://codesandbox.io/s/k58z3r9115
我还已将itemsCountPerPage
动态添加到状态