【问题标题】:Pagination Component not rendered on UI - React分页组件未在 UI 上呈现 - React
【发布时间】:2019-01-11 06:41:02
【问题描述】:

我正在尝试在我的反应应用程序using this guide 中实现分页我按照指南中的说明创建了 Pagination.js 文件,但我无法在我的 UI 上看到它,这是应用程序的屏幕截图@987654322 @

这是我实现分页的搜索结果页面,基本上这将显示根据用户输入的关键字从服务器获取的结果,因此我想显示为分页结果。我上面截图对应的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 文件中的项目列表没有被呈现。 谁能指出我到底错过了什么?

【问题讨论】:

    标签: javascript reactjs user-interface pagination


    【解决方案1】:

    您的问题是 constructor 中的 if 声明错误。所以这个:

    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);
            }
        }
    

    【讨论】:

    • 不,我相信这些行是用于渲染数据,如 item1、item2、item3 等,它与页面底部的按钮没有任何关系。我可能是错的,只是这么想,顺便说一句,我尝试了你的方法,不幸的是它不起作用。
    • 我很抱歉我误解了你的问题,但我想我可能已经找到了错误,我已经编辑了我的答案。
    • componentWillMount() 在最新的 react 版本中已被弃用,并且很快它将在即将到来的主要版本中删除,这就是我将逻辑放在构造函数中的原因。无论如何,我尝试使用 componentWillMount() 函数,但同样,它不起作用。
    【解决方案2】:

    这就是我实现上述库的方式,它真的很酷。我必须给它添加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;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多