分页组件未在UI上呈现-React

时间:2019-01-07 19:39:09

标签: javascript reactjs user-interface pagination

我正在尝试在我的React应用程序using this guide 中实现分页,我按照指南中的指示创建了Pagination.js文件,但是我无法在用户界面上看到它,这是该应用程序的屏幕截图enter image description here

这是我正在执行分页的“搜索结果”页面,基本上这将显示基于用户输入的关键字从服务器获取的结果,因此我希望显示为分页结果。与上述屏幕截图对应的我的js文件是:

import React from 'react';
import NavigationBar from './NavigationBar';
import SearchPageResultsStyle from "../assets/css/SearchResultsPage.css"
import Pagination from './Pagination';

class SearchResultsPage  extends React.Component{
    constructor(props) {
        super(props);
        console.log("Printing in the results component: this.props.location.state.data.keyword")
        console.log(this.props.location.state.data.keyword)
        this.state = {
            results: this.props.location.state.data.results,
            keyword: this.props.location.state.data.keyword,
            pageOfItems: []
        };
        this.onChangePage = this.onChangePage.bind(this);
    }

    onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
    render() {
        return(
            <div>
                <NavigationBar/>
                <h4 style={{textAlign:'center', color:'#1a0dab'}}>Showing search results for <span style={{fontWeight:'bold', fontStyle:'Italic'}}>'{this.state.keyword}'</span></h4>
                <hr/>
                <div className={'wrap'} style={SearchPageResultsStyle}>
                    <div className={'fleft'}>left column</div>
                    <div className={'fcenter'}>
                        <h3 style={{color:'#1a0dab'}}>Tweeter tweets text will be displayed here!!!</h3>
                        <a href={'https://google.com'}>Tweet urls will be displayed here</a>
                        <br/>
                        <div style={{display:'inline'}}>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>topic: </span>crime</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>city: </span>delhi</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>lang: </span>Hindi</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>Hashtags: </span></p>
                            <hr/>
                            <Pagination items={this.state.results} onChangePage={this.onChangePage}/>
                        </div>
                    </div>
                    <div className={'fright'}>right column</div>
                </div>
            </div>


        )
    }

}

export default SearchResultsPage;

我的pagination.js文件

import React from 'react';
import PropTypes from 'prop-types';

const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number,
    pageSize: PropTypes.number
};

const defaultProps = {
    initialPage: 1,
    pageSize: 10
};

class Pagination extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pager: {}
        };

        // set page if items array isn't empty
        if (this.props.items && this.props.items.length) {
            this.setPage(this.props.initialPage);
        }
    }

    componentDidUpdate(prevProps, prevState) {
        // reset page if items array has changed
        if (this.props.items !== prevProps.items) {
            this.setPage(this.props.initialPage);
        }
    }

    setPage(page) {
        var { items, pageSize } = this.props;
        var pager = this.state.pager;
        
        if (page < 1 || page > pager.totalPages) {
            return;
        }

        // get new pager object for specified page
        pager = this.getPager(items.length, page, pageSize);

        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);

        // update state
        this.setState({ pager: pager });

        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }

    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;

        // default page size is 10
        pageSize = pageSize || 10;

        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);

        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }

        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

        // create an array of pages to ng-repeat in the pager control
        var pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i);

        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }

    render() {
        var pager = this.state.pager;

        if (!pager.pages || pager.pages.length <= 1) {
            // don't display pager if there is only 1 page
            return null;
        }

        return (
            <div>
                <ul className="pagination">
                    <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(1)}>First</button>
                    </li>
                    <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.currentPage - 1)}>Previous</button>
                    </li>
                    {pager.pages.map((page, index) =>
                        <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                            <button onClick={() => this.setPage(page)}>{page}</button>
                        </li>
                    )}
                    <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.currentPage + 1)}>Next</button>
                    </li>
                    <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.totalPages)}>Last</button>
                    </li>
                </ul>
            </div>
        );
    }
}

Pagination.propTypes = propTypes;
Pagination.defaultProps = defaultProps;
export default Pagination;
我不明白为什么我的Pagination.js文件中的项目列表没有得到渲染。 有人可以指出我到底想念什么吗?

2 个答案:

答案 0 :(得分:0)

您的问题是if中的constructor语句放错了位置。所以这个:

class Pagination extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pager: {}
        };

        // set page if items array isn't empty
        if (this.props.items && this.props.items.length) {
            this.setPage(this.props.initialPage);
        }
    }

应该是:

class Pagination extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pager: {}
        }
    }

    componentWillMount() {
      if (this.props.items && this.props.items.length) {
            this.setPage(this.props.initialPage);
        }
    }

答案 1 :(得分:0)

这就是我实现上述库的方式,这真的很酷。我必须在其中添加CSS,以使其看起来不错。现在对我有用。

import React from 'react';
import NavigationBar from './NavigationBar';
import SearchPageResultsStyle from "../assets/css/SearchResultsPage.css"
import Pagination from './Pagination';

class SearchResultsPage  extends React.Component{
    constructor(props) {
        super(props);
        console.log("Printing in the results component: this.props.location.state.data.results")
        console.log(this.props.location.state.data.results)
        this.state = {
            results: this.props.location.state.data.results,
            keyword: this.props.location.state.data.keyword,
            pageOfItems: []
        };
        this.onChangePage = this.onChangePage.bind(this);
    }

    onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
    render() {

        const renderItems = this.state.pageOfItems.map((item, index) => {
            return (
                <div>
                    <h3 style={{color: '#1a0dab'}} key={index}>{item.text}</h3>
                    <a href={'https://google.com'} key={index}>{item.tweetUrl}</a>
                    <br/>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>topic: </span>{item.topic}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>city: </span>{item.city}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>lang: </span>{item.lang}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>Hashtags: </span></p>
                    <hr/>
                </div>
            )
        })
        return (
            <div>
                <NavigationBar/>
                <h4 style={{textAlign:'center', color:'#1a0dab'}}>Showing search results for <span style={{fontWeight:'bold', fontStyle:'Italic'}}>'{this.state.keyword}'</span></h4>
                <hr/>
                <div className={'wrap'} style={SearchPageResultsStyle}>
                    <div className={'fleft'}>left column</div>
                    <div className={'fcenter'}>
                        {renderItems}
                        <Pagination items={this.state.results} onChangePage={this.onChangePage}/>
                    </div>
                </div>
                <div className={'fright'}></div>
            </div>
        )
    }

}

export default SearchResultsPage;