Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 不使用异步ajax进行反应分页渲染_Javascript_Reactjs_Pagination_React State_React State Management - Fatal编程技术网

Javascript 不使用异步ajax进行反应分页渲染

Javascript 不使用异步ajax进行反应分页渲染,javascript,reactjs,pagination,react-state,react-state-management,Javascript,Reactjs,Pagination,React State,React State Management,我是新手,我遵循了本教程:但它只显示JSON就绪数据的分页,而不显示ajax获取的数据 这是我的父组件(SearchCountry): 从“Countries api/lib/data/Countries.json”导入国家; 导出默认类SearchCountry扩展组件{ /* |-------------------------------------------------------------------------- |建造师 |---------------------------

我是新手,我遵循了本教程:但它只显示JSON就绪数据的分页,而不显示ajax获取的数据

这是我的父组件(SearchCountry):

从“Countries api/lib/data/Countries.json”导入国家;
导出默认类SearchCountry扩展组件{
/*
|--------------------------------------------------------------------------
|建造师
|--------------------------------------------------------------------------
*/
建造师(道具){
超级(道具);
此.state={
searchData:null,
错误:null,
showModal:错,
所有国家:[],
当前国家:[],
当前页面:空,
totalPages:空
};
this.modal=[];
this.getSearchData=this.getSearchData.bind(this);
this.onPageChanged=this.onPageChanged.bind(this);
}
/*
|--------------------------------------------------------------------------
|获取搜索数据
|--------------------------------------------------------------------------
*/
异步getSearchData(页码=1){
const url=webRoot+`searchcountry/searchajax?page=${pageNumber}`;
//获取响应数据
const response=wait axios.get(url);
//设置“searchData”状态
this.setState({searchData:response.data});
//设置“searchData”状态
this.setState({allCountries:response.data.countries.data});
};
/*
|--------------------------------------------------------------------------
|组件没有安装
|--------------------------------------------------------------------------
*/
异步组件didmount(){
等待此消息。getSearchData();
//-如果我取消对此的注释,它会工作,因为它是json数据
//const allCountries=国家;
//这个.setState({allCountries});
}
/*
|--------------------------------------------------------------------------
|第页已更改
|--------------------------------------------------------------------------
*/
onPageChanged=数据=>{
const{allCountries}=this.state;
const{currentPage,totalPages,pageLimit}=数据;
常量偏移量=(当前页面-1)*页面限制;
const currentCountries=allCountries.slice(偏移量,偏移量+页面限制);
this.setState({currentPage,currentCountries,totalPages});
};
/*
|--------------------------------------------------------------------------
|渲染
|--------------------------------------------------------------------------
*/
render(){
log('Render:Main Component-->');
const totalAlbums=this.state.totalAlbums;
const currentAlbums=this.state.currentAlbums;
const renderResults=(this.state.allCountries?:“”);
常数{
所有国家,
当前国家,
当前页,
总页数
}=本州;
const totalCountries=allCountries.length;
const renderTopPagination=(this.state.allCountries?
: '');
返回(
{renderTopPagination}
{renderResults}
}
这是我的子组件(分页):

import React,{Component,Fragment}来自“React”;
从“道具类型”导入道具类型;
const LEFT_PAGE=“LEFT”;
const RIGHT_PAGE=“RIGHT”;
常数范围=(从,到,步长=1)=>{
让我=来自;
常数范围=[];
而{
const{onPageChanged=f=>f}=this.props;
const currentPage=Math.max(0,Math.min(page,this.totalPages));
常数分页数据={
当前页,
totalPages:this.totalPages,
pageLimit:this.pageLimit,
totalRecords:this.totalRecords
};
this.setState({currentPage},()=>onPageChanged(paginationData));
};
/*
|--------------------------------------------------------------------------
|手柄点击
|--------------------------------------------------------------------------
*/
handleClick=(第页,evt)=>{
evt.preventDefault();
本页:gotoPage(第页);
};
/*
|--------------------------------------------------------------------------
|把手向左移动
|--------------------------------------------------------------------------
*/
handleMoveLeft=evt=>{
evt.preventDefault();
this.gotoPage(this.state.currentPage-this.pageneights*2-1);
};
/*
|--------------------------------------------------------------------------
|把手向右移动
|--------------------------------------------------------------------------
*/
手控灯=evt=>{
evt.preventDefault();
this.gotoPage(this.state.currentPage+this.pageneights*2+1);
};
/*
|--------------------------------------------------------------------------
|获取页码
|--------------------------------------------------------------------------
*/
fetchPageNumber=()=>{
const totalPages=this.totalPages;
const currentPage=this.state.currentPage;
const pageneights=this.pageneights;
const totalNumbers=this.pageneights*2+3;
const totalBlocks=totalNumbers+2;
如果(totalPages>totalBlocks){
让pages=[];
const leftBound=当前页面-页面邻居;
const rightbund=当前页面+页面邻居;
const beforeLastPage=totalPages-1;
常量起始页=左边界>2?左边界:2;
const endPage=righboundimport 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,
            currentCountries,
            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, ...extraPages, rightSpillPage];
            } else if (leftSpill && rightSpill) {
                pages = [leftSpillPage, ...pages, rightSpillPage];
            }

            return [1, ...pages, 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;