Компонент пагинации не отображается в пользовательском интерфейсе - React - PullRequest
0 голосов
/ 07 января 2019

Я пытаюсь реализовать разбиение на страницы в своем приложении реагирования , используя это руководство Я создал файл 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 голосов
/ 11 января 2019

Вот как я реализовал вышеупомянутую библиотеку, это действительно классная библиотека. Я должен добавить 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;
0 голосов
/ 08 января 2019

Ваш вопрос неуместен 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);
        }
    }
...