reactjs - 分页问题,有一次我迷路了
问题描述
我正在尝试对 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
}
我不知道如何在我的分页组件中使用它。
解决方案
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。
还要处理一些边缘情况。
推荐阅读
- php - 如何解决这个 PHP 错误“只有变量应该通过引用传递”?
- c# - 选择查询值可以为空的查询
- oracle - 为 CREATE DDL 语句创建了带有编译错误的触发器:PLS-00103:遇到符号“CREATE”
- python - 未显示 y 轴的 Plotly/Dash 标题
- sql - Sql Query 获取汇总计数
- java - Symfony JAVA_HOME 未设置
- c# - SqlDataReader 在尝试将数据加载到 DataGrid WPF 时抛出异常
- qt - 我可以在 Qt 的 QTextDocument 中使用自定义标签吗?
- delphi - 如何设置时间和日期警报?
- json - 为什么每次将 json 文件与 ajax 请求连接时都会出现 304 错误?