如何解决反应分页不渲染与异步ajax
我是REACT的新手,我按照本教程进行了学习:https://www.digitalocean.com/community/tutorials/how-to-build-custom-pagination-with-react
,但它仅显示针对JSON就绪数据的分页,而不显示ajax获取的数据
这是我的父组件(SearchCountry):
import Countries from "countries-api/lib/data/Countries.json";
export default class SearchCountry extends Component {
/*
|--------------------------------------------------------------------------
| Constructor
|--------------------------------------------------------------------------
*/
constructor(props) {
super(props);
this.state = {
searchData: null,error: null,showModal: false,allCountries: [],currentCountries: [],currentPage: null,totalPages: null
};
this.modal = [];
this.getSearchData = this.getSearchData.bind(this);
this.onPageChanged = this.onPageChanged.bind(this);
}
/*
|--------------------------------------------------------------------------
| Get Search Data
|--------------------------------------------------------------------------
*/
async getSearchData(pageNumber = 1) {
const url = webRoot + `searchcountry/searchajax?page=${pageNumber}`;
// Get Response Data
const response = await axios.get(url);
// Set 'searchData' State
this.setState({ searchData: response.data });
// Set 'searchData' State
this.setState({ allCountries: response.data.countries.data });
};
/*
|--------------------------------------------------------------------------
| Component Did Mount
|--------------------------------------------------------------------------
*/
async componentDidMount() {
await this.getSearchData();
// - If I uncomment this it works because it is json data
//const allCountries = Countries;
//this.setState({ allCountries });
}
/*
|--------------------------------------------------------------------------
| On Page Changed
|--------------------------------------------------------------------------
*/
onPageChanged = data => {
const { allCountries } = this.state;
const { currentPage,totalPages,pageLimit } = data;
const offset = (currentPage - 1) * pageLimit;
const currentCountries = allCountries.slice(offset,offset + pageLimit);
this.setState({ currentPage,currentCountries,totalPages });
};
/*
|--------------------------------------------------------------------------
| Render
|--------------------------------------------------------------------------
*/
render() {
console.log('Render : Main Component -----> ');
const totalAlbums = this.state.totalAlbums;
const currentAlbums = this.state.currentAlbums;
const renderResults = (this.state.allCountries ? <Results albums={this.state.searchData}/> : '');
const {
allCountries,currentPage,totalPages
} = this.state;
const totalCountries = allCountries.length;
const renderTopPagination = (this.state.allCountries ?
<Pagination
totalRecords={totalCountries}
pageLimit={3}
pageNeighbours={1}
onPageChanged={this.onPageChanged}
/> : '');
return (
<React.Fragment>
<div>
{renderTopPagination}
</div>
<div>
{renderResults}
</div>
</React.Fragment>
}
这是我的孩子部分(分页):
import React,{ Component,Fragment } from "react";
import PropTypes from "prop-types";
const LEFT_PAGE = "LEFT";
const RIGHT_PAGE = "RIGHT";
const range = (from,to,step = 1) => {
let i = from;
const range = [];
while (i <= to) {
range.push(i);
i += step;
}
return range;
};
/*
|--------------------------------------------------------------------------
| Component : Pagination
|--------------------------------------------------------------------------
*/
class Pagination extends Component {
/*
|--------------------------------------------------------------------------
| Constructor
|--------------------------------------------------------------------------
*/
constructor(props) {
super(props);
const { totalRecords = null,pageLimit = 30,pageNeighbours = 0 } = props;
this.pageLimit = typeof pageLimit === "number" ? pageLimit : 30;
this.totalRecords = typeof totalRecords === "number" ? totalRecords : 0;
this.pageNeighbours =
typeof pageNeighbours === "number"
? Math.max(0,Math.min(pageNeighbours,2))
: 0;
this.totalPages = Math.ceil(this.totalRecords / this.pageLimit);
this.state = { currentPage: 1 };
}
/*
|--------------------------------------------------------------------------
| Component Did Mount
|--------------------------------------------------------------------------
*/
componentDidMount() {
this.gotoPage(1);
}
/*
|--------------------------------------------------------------------------
| Goto Page
|--------------------------------------------------------------------------
*/
gotoPage = page => {
const { onPageChanged = f => f } = this.props;
const currentPage = Math.max(0,Math.min(page,this.totalPages));
const paginationData = {
currentPage,totalPages: this.totalPages,pageLimit: this.pageLimit,totalRecords: this.totalRecords
};
this.setState({ currentPage },() => onPageChanged(paginationData));
};
/*
|--------------------------------------------------------------------------
| Handle Click
|--------------------------------------------------------------------------
*/
handleClick = (page,evt) => {
evt.preventDefault();
this.gotoPage(page);
};
/*
|--------------------------------------------------------------------------
| Handle Move Left
|--------------------------------------------------------------------------
*/
handleMoveLeft = evt => {
evt.preventDefault();
this.gotoPage(this.state.currentPage - this.pageNeighbours * 2 - 1);
};
/*
|--------------------------------------------------------------------------
| Handle Move Right
|--------------------------------------------------------------------------
*/
handleMoveRight = evt => {
evt.preventDefault();
this.gotoPage(this.state.currentPage + this.pageNeighbours * 2 + 1);
};
/*
|--------------------------------------------------------------------------
| Fetch Page Numbers
|--------------------------------------------------------------------------
*/
fetchPageNumbers = () => {
const totalPages = this.totalPages;
const currentPage = this.state.currentPage;
const pageNeighbours = this.pageNeighbours;
const totalNumbers = this.pageNeighbours * 2 + 3;
const totalBlocks = totalNumbers + 2;
if (totalPages > totalBlocks) {
let pages = [];
const leftBound = currentPage - pageNeighbours;
const rightBound = currentPage + pageNeighbours;
const beforeLastPage = totalPages - 1;
const startPage = leftBound > 2 ? leftBound : 2;
const endPage = rightBound < beforeLastPage ? rightBound : beforeLastPage;
pages = range(startPage,endPage);
const pagesCount = pages.length;
const singleSpillOffset = totalNumbers - pagesCount - 1;
const leftSpill = startPage > 2;
const rightSpill = endPage < beforeLastPage;
const leftSpillPage = LEFT_PAGE;
const rightSpillPage = RIGHT_PAGE;
if (leftSpill && !rightSpill) {
const extraPages = range(startPage - singleSpillOffset,startPage - 1);
pages = [leftSpillPage,...extraPages,...pages];
} else if (!leftSpill && rightSpill) {
const extraPages = range(endPage + 1,endPage + singleSpillOffset);
pages = [...pages,rightSpillPage];
} else if (leftSpill && rightSpill) {
pages = [leftSpillPage,...pages,rightSpillPage];
}
return [1,totalPages];
}
return range(1,totalPages);
};
/*
|--------------------------------------------------------------------------
| Render
|--------------------------------------------------------------------------
*/
render() {
if (!this.totalRecords) return null;
if (this.totalPages === 1) return null;
const { currentPage } = this.state;
const pages = this.fetchPageNumbers();
console.log('pages ---> ' + pages);
return (
<Fragment>
<div className="c-pagination">
<div className="c-pagination-items">
{currentPage !== 1 ? <div key={'first-btn'} className="c-pagination-item c-pagination-item--control" onClick={e => this.handleClick(1,e)}>
First
</div> : null}
{pages.map((page,index) => {
if(page === 1) {
if(currentPage !== 1) {
return null;
}
}
if(page === this.totalPages) {
if(currentPage !== this.totalPages) {
return null;
}
}
if (page === LEFT_PAGE)
return (
<div key={index} className="c-pagination-item c-pagination-item--control" onClick={this.handleMoveLeft}>
Prev
</div>
);
if (page === RIGHT_PAGE)
return (
<div key={index} className="c-pagination-item c-pagination-item--control" onClick={this.handleMoveRight}>
Next
</div>
);
return (
<div
key={index}
className={`c-pagination-item ${ currentPage === page ? 'c-pagination-item--active' : ''}`} onClick={e => this.handleClick(page,e)}
>
{page}
</div>
);
})}
{currentPage !== this.totalPages ? <div key={'last-btn'} className="c-pagination-item c-pagination-item--control" onClick={e => this.handleClick(this.totalPages,e)}>
Last
</div> : null}
</div>
</div>
</Fragment>
);
}
}
Pagination.propTypes = {
totalRecords: PropTypes.number.isRequired,pageLimit: PropTypes.number,pageNeighbours: PropTypes.number,onPageChanged: PropTypes.func
};
export default Pagination;
问题: 分页将不会显示,因为第一次呈现时,异步Ajax调用无法及时完成。如何在第一次呈现网页时显示分页(子组件)?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。