在Next JS中实现Load More按钮



我正在使用Next JS的SWR包。我能够使用这些来获取数据,并能够在表中显示该数据。

但是现在我想在清单的页面上显示加载更多类型的分页。下面是我的代码:

位置组件:

import useSWR, { useSWRPages } from 'swr'
import axios from 'axios'
import { useState } from 'react'
//... other dependencies import
export default function Locations({...props}) {
const [loading,setLoading] = useState(true)
const [dataCount, setDataCount] = useState(3);
const [pageIndex, setPageIndex] = useState(1)    
const locationsFetcher = async() => {
let response = await axios( process.env.url + '?page=${pageIndex}&limit=${dataCount}', headers:{})
setLoading(false)
let data = await response.data.results
return data;
}
const {data, error} = useSWR('locations', locationsFetcher,{
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (error.status === 404) return
if (retryCount >= 10) return

setTimeout(() => revalidate({ retryCount }), 5000)
}
})
const loadMore = () => {
console.log("count " + dataCount +  " pageIndex " + pageIndex)
setDataCount(dataCount + 3)
setPageIndex(pageIndex + 1)
}

return (
<>
<table>
{error && <tr><td><p>Error in Loading Data. </p></td></tr>}
{(loading) ? <tr><td colSpan="6"><p>Loading ...</p></td></tr> : 
(data && data.length > 0) ? (data.map((location, index) => (
<tr index={index} key={index}>
<td>{location.name}</td>
...

<td>{location.phone}</td>
</tr>
))) : (<tr><td><NoDataFound  /></td></tr>)}
</table>
<div className="click_btn">
<button onClick={() => loadMore()}>
<span>Expande Table</span>
</button>
</div>
</>

}

我能够在控制台日志中看到页面和限制的更新状态值,但无法调用API并在清单上显示更新的数据。

按照https://swr.vercel.app/docs/pagination

您需要将url作为useSWR的第一个参数,并且您还应该使用'而不是'。

const {data, error} = useSWR(process.env.url + `?page=${pageIndex}&limit=${dataCount}`, locationsFetcher,{
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (error.status === 404) return
if (retryCount >= 10) return

setTimeout(() => revalidate({ retryCount }), 5000)
}
})

最新更新