【问题标题】:Reusable React Pagination Component可重用的 React 分页组件
【发布时间】:2019-11-17 22:13:02
【问题描述】:

我正在尝试使用reactstrap 作为 UI 库创建动态分页反应组件。我被困在完成相同的问题上。

UsersCard.js

import React, { Component } from 'react'
import axios from 'axios';
import PaginationTable from './PaginationTable';



    export default class UsersCard extends Component {

        constructor(props) {
          super(props)

          this.state = {
              usersData: [],
              loading: false,
              per_page: 3,
              current_page: 1,
              total_data: '',
              currentPosts: []
          }
        }

    async componentDidMount(){
      await axios.get('https://reqres.in/api/users')
        .then(res => {
            this.setState({
              usersData: res.data.data,
              loading: false,
              total_data: res.data.data.length
            })
        })
        .catch(err => console.log(err));

        const indexOfLastPost = this.state.current_page * this.state.per_page;
        const indexOfFirstPage = indexOfLastPost - this.state.per_page;

        const currentPosts = this.state.usersData.slice(indexOfFirstPage, indexOfLastPost);

        this.setState({ currentPosts })

    }

    handleClick = (number) => {
      this.setState({
        current_page: number
      })
    }

      render() {
        const { per_page, handleClick, total_data, current_page, currentPosts } = this.state;

        return (
          <div>
            <table>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>First Name</th>
                        <th>email</th>
                        <th>Last Name</th>
                    </tr>
                </thead>
                {currentPosts.map(x => {
                return(
                        <React.Fragment key={x.id}>
                                <tbody>
                                    <tr>
                                        <td>{x.id}</td>
                                        <td>{x.first_name}</td>
                                        <td>{x.email}</td>
                                        <td>{x.last_name}</td>
                                    </tr>
                                </tbody>
                        </React.Fragment>
                        )
                })}
            </table>
            <PaginationTable
                      per_page={per_page}
                      current_page={current_page}
                      total_data={total_data}
                      handleClick={handleClick}
                    />
          </div>
        )
      }
    }

PaginationTable.js

import React from 'react';
import { Pagination, PaginationItem, PaginationLink } from 'reactstrap';

const PaginationTable = ({ per_page, total_data, handleClick, current_page }) => {

    let pageNumbers = [];

    for(let i=1; i<= Math.ceil(total_data/per_page); i++)
    {   
        pageNumbers.push(
        <PaginationItem key={i} active={current_page === i ? true : false}>
            <PaginationLink onClick={() => handleClick(i)} href="#">
                {i}
            </PaginationLink>
        </PaginationItem>)
    }



    return(
            <Pagination aria-label="Page navigation example">
                <PaginationItem disabled={current_page <= 1}>
                    <PaginationLink onClick={()=>handleClick(current_page-1)}
                            previous 
                            href="#" 
                    />
                    </PaginationItem>

                        {pageNumbers}

                <PaginationItem disabled={current_page >= per_page - 1}>
                    <PaginationLink onClick={()=>handleClick(current_page + 1)}
                            next 
                            href="#" 
                    />
                </PaginationItem>
            </Pagination>

    )

}

导出默认分页表;

我的问题是这样的:

1) Reactstrap 分页 UI 未正确显示。

2) 每当我单击next 按钮时,它都会显示错误:TypeError: handleClick is not a function

我对动态分页概念有点陌生,无法识别我遇到的错误。 Kindlt帮助解决同样的问题。也欢迎任何代码改进。

【问题讨论】:

  • 你必须从父组件传递this.handleClick
  • 它确实让我摆脱了点击错误,但它不起作用:/。你能帮忙吗?
  • @BoyWithSilverWings 你能帮我解决这个问题吗?这是演示链接:react-qxrpv8.stackblitz.io

标签: javascript reactjs pagination


【解决方案1】:

这种方法存在多个问题:

  1. this.handleClick 必须从父级传入。

  2. setState 函数是异步的。因此,在设置后立即访问状态可能不会导致您希望的相同状态。为了解决这个问题,React 给你一个回调函数作为第二个参数。这仅在状态运行后运行。

  3. 在更改分页后,您没有更新 currentPosts 状态。分页组件只关心更改页码,数据的更改必须手动处理。您可以通过以下方式处理:

  async componentDidMount() {
    await axios
      .get("https://reqres.in/api/users")
      .then(res => {
        this.setState({
          usersData: res.data.data,
          loading: false,
          total_data: res.data.data.length
        }, () => {
          this.formatData();
        });
      })
      .catch(err => console.log(err));
  }

  formatData() {
    const indexOfLastPost = this.state.current_page * this.state.per_page;
    const indexOfFirstPage = indexOfLastPost - this.state.per_page;

    const currentPosts = this.state.usersData.slice(
      indexOfFirstPage,
      indexOfLastPost
    );

    this.setState({ currentPosts });
  }

  handleClick = number => {
    this.setState({
      current_page: number
    }, () => {
      this.formatData();
    });
  };

Updated Stackblitz

【讨论】:

  • 那是我的大小姐。非常感谢这位朋友!
【解决方案2】:

关于第一个。您正在尝试仅在 pageNumbers 中呈现一组 jsx 元素。取而代之的是 - 你可以将数字推入这个数组:

let pageNumbers = [];

for(let i=1; i<= Math.ceil(total_data/per_page); i++)
{   
  pageNumbers.push(i)
}

然后使用地图直接渲染分页项。

{pageNumbers.map(i => (
  <PaginationItem key={i} active={current_page === i ? true : false}>
      <PaginationLink onClick={() => handleClick(i)} href="#">
         {i}
      </PaginationLink>
   </PaginationItem>
))}

关于第二个:handleClick 不是一个函数,因为您首先在渲染函数之上定义它,然后在解构状态时覆盖它,但是您的状态中没有 handleClick 这样的东西,所以它分配给 null 或 undefined。 您所要做的就是在解构赋值中删除它并将其作为this.handleClick 传递,它应该可以工作。

【讨论】:

  • 你能分享更多细节现在什么不起作用吗?它是如何渲染的?还是根本不渲染?
  • 你能帮忙解决这个问题吗? react-qxrpv8.stackblitz.io
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 2020-10-02
  • 2021-08-14
  • 2020-10-13
  • 2015-01-03
  • 2017-02-09
  • 1970-01-01
  • 2020-05-11
相关资源
最近更新 更多