我正在尝试使用 nextjs 和 useSWR 挂钩创建分页。
这就是我目前的做法,它似乎正在工作......但是我在文档中读到,作为第一个参数传递的密钥应该是一个唯一的字符串(通常是一个 URL)。我只是传递索引来获取正确的数据。我的方法会扰乱缓存吗?我不确定我这样做是否正确?
index.js
import React, { useState } from 'react'
import Page from '../components/page'
export default function IndexPage( ) {
const [pageIndex, setPageIndex] = useState(0)
return (
<div>
<Page index={pageIndex} />
<button onClick={() => setPageIndex(pageIndex - 1)}>Previous</button>
<button onClick={() => setPageIndex(pageIndex + 1)}>Next</button>
</div>
)
}
而在我的page.js
import useSWR from 'swr'
import { fetcher } from '../client/fetcher'
function Page({ index }) {
const { data } = useSWR(index, fetcher)
console.table(data)
return <div>nothing here, just testing</div>
}
export default Page
最后是fetcher.js
import client from './contentful-client'
export async function fetcher(pageIndex = 1, limit = 3) {
const data = await client.getEntries({
content_type: 'posts',
skip: pageIndex * limit,
order: '-fields.publishDate',
limit,
})
if (data) {
return data
}
console.log('Something went wrong fetching data')
}
您可能希望将内容数据获取逻辑移至服务器,以免向浏览器公开凭据和逻辑。这可以使用以下方法完成Next.js API 路由 https://nextjs.org/docs/api-routes/introduction.
// pages/api/posts.js
import client from '<path-to>/contentful-client' // Replace with appropriate path to file
export default async function handler(req, res) {
const { pageIndex = 1, limit = 3 } = req.query
const data = await client.getEntries({
content_type: 'posts',
skip: pageIndex * limit,
order: '-fields.publishDate',
limit,
})
res.json(data)
}
然后,您可以重构页面中的代码,以针对新创建的 API 路由发出请求,并将路由 URL 作为密钥传递给useSWR
.
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then(res => res.json())
function Page({ index }) {
const { data } = useSWR(`/api/posts?pageIndex=${index}`, fetcher)
console.table(data)
return <div>nothing here, just testing</div>
}
export default Page
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)