我正在使用Marvel API创建一个应用,并且想要实现分页。
这是获取数据的动作,作为回应,我可以获得项目的总数,偏移量,限制,计数;
export const fetchData = (name) => async dispatch => {
const response = await fetch(`https://gateway.marvel.com/v1/public/${name}?apikey=${API_KEY}&ts=${ts}&hash=${hash}`);
const data = await response.json();
const totalPages = Math.ceil(data.data.total / data.data.count);
const count = data.data.count;
const offset = data.data.offset;
const results = await data.data.results;
dispatch({
type: FETCH_DATA_ACTION,
data: results,
totalPages,
count,
offset
});
}
分页组件的父项
class ComicsList extends Component {
componentDidMount() {
this.props.fetchData('comics');
}
onSetPage(i, count, offset) {
this.props.setPage(i, count, offset);
}
render() {
const {comics, totalPages, count, offset } = this.props;
return (
<div>
<div className="row">{comics ? comics.map((comic) => {
return <ComicsCard comic={comic} key={comic.id}/>;
}) : <span>Loading data</span>}</div>
<Pagination totalPages={totalPages} onSetPage={(i) => this.onSetPage(i, count, offset)} />
</div>
);
}
}
分页组件本身
export class Pagination extends Component {
setPage(i) {
this.props.onSetPage(i);
}
render() {
const { totalPages } = this.props;
const createPages = () => {
let pages = [];
for(let i = 1; i <= totalPages; i++) {
pages.push(
<li className="waves-effect" key={i} onClick={() => this.setPage(i)}><a>{i}</a></li>
);
}
return pages;
};
return (
<ul className="pagination">
<li className="disabled"><a href="#!"><i className="material-icons">chevron_left</i></a></li>
{ createPages() }
<li className="waves-effect"><a href="#!"><i className="material-icons">chevron_right</i></a></li>
</ul>
);
}
}
从我的分页组件中,我还可以返回当前页面。
我当时正在考虑计算偏移量,然后调用通过查询字符串获取数据的操作,但是我不确定如何根据页数和计数来实际计算偏移量吗?
export const setPage = (current_page, count, offset) => async dispatch => {
console.log(current_page, count, offset)
}