簡體   English   中英

可重用的 React 分頁組件

[英]Reusable React Pagination Component

我正在嘗試使用reactstrap作為 UI 庫創建動態分頁反應組件。 我被困在完成相同的問題上。

用戶卡.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>
        )
      }
    }

分頁表.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>

    )

}

導出默認分頁表;

我的問題 go 像:

1) Reactstrap 分頁 UI 沒有正確顯示。

2)每當我單擊next按鈕時,它都會顯示錯誤: TypeError: handleClick is not a function

我對動態分頁概念有點陌生,無法識別我遇到的錯誤。 Kindlt幫助解決同樣的問題。 也歡迎任何代碼改進。

這種方法存在多個問題:

  1. this.handleClick必須從父級傳入。

  2. setState function 是異步的。 因此,在設置后立即訪問 state 可能不會產生您希望的相同 state。 為了解決這個問題,React 給你一個回調 function 作為第二個參數。 這僅在 state 運行后運行。

  3. 更改分頁后,您沒有更新currentPosts state。 分頁組件只關心更改頁碼,數據的更改必須手動處理。 您可以通過以下方式處理此問題:

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

更新了 Stackblitz

關於第一個。 您正在嘗試僅在pageNumbers中呈現一組 jsx 元素。 取而代之的是-您可以將數字推入此數組:

let pageNumbers = [];

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

然后直接在應該使用 map 的地方渲染分頁項目。

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

About the second: handleClick is not a function because you are first defining it above the render function and then you are overriding it when destructuring state, but there is no such thing as handleClick in your state, so it is assigned to null or undefined. 您所要做的就是在解構賦值中刪除它並將其作為this.handleClick傳遞,它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM