简体   繁体   English

如何使用 getServerSideProps 在 Next JS 中添加分页 API

[英]how to add pagination API in Next JS with getServerSideProps

I have to add a param that changes ( page=1 ) it should be ( page=${setPage} )我必须添加一个更改的参数 ( page=1 ) 它应该是 ( page=${setPage} )

then when you press the button that changes the data of the table.然后当您按下更改表格数据的按钮时。

This is how I have my code in [table].js这就是我在[table].js中的代码

How can I do to change that?我该怎么做才能改变它? Or should I use useEffect for the fetch?或者我应该使用 useEffect 来获取?

What would be the appropriate method to be able to change the page or add pagination to my table by changing the value of page通过更改 page 的值来更改页面或向我的表添加分页的适当方法是什么

import React, { useState, useEffect } from 'react'
import {
    Heading,
    Box,
    Text,
    Button,
    Flex,
    Input,
    Select,
    InputGroup,
    InputLeftElement, HStack, Center
} from '@chakra-ui/react'
import { useRouter } from 'next/router'
    
import TablesData from '../../components/tables/Tablesdata'
    
const UnderWriting = (props) => {
    const { data } = props
    console.log('data', data)

    const [dataToShow, setDataToShow] = useState(data)
    const [title, setTitle] = useState('')
    const [pageIndex, setPageIndex] = useState(1)

    const router = useRouter()
    const { tabla } = router.query

    useEffect(() => {
        switch (tabla) {
            case 'primera': {
                setTitle('Primera revision de UW')
                break
            }
            case 'segunda': {
                setTitle('Segunda revision de UW')
                break
            }
            case 'seguimiento': {
                setTitle('En Seguimiento UW')
                break
            }
            case 'cartera': {
                setTitle('Cartera de UW')
                break
            }
        }
        setDataToShow(data)
    }, [tabla, data])

    return (
        <Box>
            <Box> 
                <Box color='#96A0AA' border='1px solid #DFE6EE' boxShadow='lg' overflow='hidden' rounded='lg'>
                    <TablesData data={dataToShow}  />
                </Box>
                <Center>
                    <HStack mt={5} mb={5} >
                        <Button  >
                            Anterior
                        </Button>
                        <Button >
                            Siguiente
                        </Button>
                    </HStack>
                </Center>
            </Box>
        </Box>
    );
}

export async function getServerSideProps(context) {
    const { params, res } = context
    const { tabla } = params
    // Fetch data from external API
    const apiResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL}admin/users/signup-status?page=1&page_size=25&`)
    if (apiResponse.ok) {
        let responseData = await apiResponse.json()
        console.log(responseData)

        const mapped = responseData.results.map(user => {
            return {
                ...user,
                wait_time: parseInt(user.wait_time.split(' ')[0]) || 0
            }
        })
        let data = mapped

        // prepara la data correspondiente solo a la que se solicita
        if (tabla === 'cartera') {
            data = mapped.map(user => {
                const dataUser = { ...user }
                delete dataUser.wait_time
                return dataUser
            })
        } else {
            data = mapped.filter(user => {
                if (tabla === 'primera') {
                    return user.status === 'revision'
                }
                if (tabla === 'segunda') {
                    return user.status === 'segunda'
                }
                if (tabla === 'seguimiento') {
                    return user.status === 'seguimiento' || user.status === 'caducado'
                }
            })
            if (tabla === 'primera') {
                data = data.map(user => {
                    const dataUser = { ...user }
                    delete dataUser.comments
                    return dataUser
                })
            }
        }

        //add pagination
        const totalPages = Math.ceil(responseData.count / 25)
        const pages = []
        for (let i = 1; i <= totalPages; i++) {
            pages.push(i)
        }

        // Pass data to the page via props
        return {
            props: {
                data,
                pages
            }
        }
    }

    if (res) {
        res.writeHead(301, { location: '/404' }).end()
    }
}

export default UnderWriting;

I assume you will be changing page numbers using query (not params).我假设您将使用查询(而不是参数)更改页码。

URL: "/[table]?page=${pageNumber}" URL: "/[table]?page=${pageNumber}"

You can read pageNumber from the context (context.query) parameter received by getServerSideProps.您可以从 getServerSideProps 收到的上下文 (context.query) 参数中读取 pageNumber。

const { page } = context.query;

Once you have the page number you can fetch data.一旦你有了页码,你就可以获取数据。 Instead of using FETCH API to get data, you can directly make a database query inside the getServerSideProps function.您可以直接在 getServerSideProps function 内部进行数据库查询,而不是使用 FETCH API 来获取数据。

Whenever the page number is changed this component will be called again and the getServerSideProps function will fetch new data based on the page number.每当页码更改时,将再次调用此组件,getServerSideProps function 将根据页码获取新数据。

Pagination JSX:分页 JSX:

return(
<>
  {props.pages.map(page) => (
    <Link href={`/table?page${page}`}>
      <button>page</button>
    </Link>
  )}
</>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM