首页 > 解决方案 > 分页问题,​​有一次我迷路了

问题描述

我正在尝试对 rickandmortyapi.com 的页面进行分页,我遇到了问题。

我用 axios 调用 api:

// get all characters
export const getCharacters = async () => {
  let response = await Axios.get(`https://rickandmortyapi.com/api/character/`)

  return response.data
}

有了这个请求,我可以映射和显示字符。

为了进行分页,我创建了一个名为 Pagination 的组件,但是在更改 getCharacters 函数的响应并在端点末尾插入 ?page=2 时遇到了问题。

分页组件:

import React, { useState, useEffect } from 'react'
import { getCharacters } from '../../API'

const Pagination = () => {
  // use state to keep track of the current page
  const [pagination, setPagination] = useState([])
  // use effect to fetch the characters
  useEffect(() => {
    // async function
    async function getPages() {
      const responsePages = await getCharacters()
      setPagination(responsePages)
      return responsePages
    }
    // call the function
    getPages()
  }, [])
  console.log(pagination)

  return (
    // pagination
    <div>
      <button
        onClick={() => {
          // I dont know what to do with this
        }}
      >
        Next
      </button>
    </div>
  )
}

export default Pagination

更新:

我做了另一个api调用:

// paginate characters
export const getCharactersPaginated = async (page) => {
  let response = await Axios.get(
    `https://rickandmortyapi.com/api/character/?page=${page}`
  )
  return response.data
}

我不知道如何在我的分页组件中使用它。

标签: reactjs

解决方案


export const getCharacters = async (page = 1) => {
  let response = await Axios.get(`https://rickandmortyapi.com/api/character/?page=${page}`)

  return response.data
}
const [currentPage, setCurrentPage] = useState(1); 
  useEffect(() => {
  const responsePages = await getCharacters(page); 
  setPagination(responsePages); 
}, [currentPage]); 

您可以更改当前页面 onClick。

还要处理一些边缘情况。


推荐阅读