useSWRInfinite - getKey函数总是得到pageIndex为1



我使用此处(https://github.com/vercel/swr/discussions/732)和此处(https://swr.vercel.app/examples/infinite-loading)定义的SWRInfinite示例。

我的代码如下…

import React from 'react'
import {useSelector} from 'react-redux'
import useSWRInfinite from 'swr/infinite'
import {Button, Grid, Typography} from '@material-ui/core'
import getNearbyShops from '../../../lib/nearshop-apis.js'
import ShopThumbnail from './shop-thumbnail.js'
import Spacer from '../../../components/utils/spacer'
const PAGE_SIZE=10
export default function Nearbyshops({category, categoryName}) {
const getKey = (pageIndex, previousPageData, category) => {
console.log("getKey::pageIndex", pageIndex)
// reached the end?
if (previousPageData && !previousPageData.data) return null
return [`/api/nearbyshops/${pageIndex+1}`, pageIndex+1, PAGE_SIZE, category]
}

const {data, error, size, setSize} = useSWRInfinite ( getKey, getNearbyShops)
const shops = data ? [].concat(...data) : [];
const isLoadingInitialData = !data && !error;
const isLoadingMore =
isLoadingInitialData || (size > 0 && data && typeof data[size-1] === 'undefined')
//const isEmpty = data[0].length === 0;
const isEmpty = data?.[0]?.length === 0;
const isReachingEnd =
isEmpty || (data && data[data.length-1].length < PAGE_SIZE);
//const isRefreshing = isValidating && data && data.length===size;
const currentShop = useSelector(state => state.main.currentShop);
const bg = currentShop.sColor
const fg = currentShop.pColor
const title = categoryName?`NEAR BY ${categoryName} SHOPS`:'NEAR BY SHOPS'
return (
<Grid>
<Typography variant='body2' style={{fontWeight:'bold',color:fg,marginTop:"12px",boxShadow: "0px 2px 2px rgba(0, 0, 0, 0.25)"}}>{title}</Typography>
<Spacer space={2}/>
{
shops.map((shop, index) => {
return <ShopThumbnail key={shop.id} shop={shop} showDistance={true} />
})
}
<Button
style={{backgroundColor:fg, color:bg}}
disabled={isLoadingMore || isReachingEnd}
onClick={() => setSize(size+1)}
variant='contained'
fullWidth
>
{
isLoadingMore
? "Loading..."
: isReachingEnd
? "No more shops"
: "Show More"
}
</Button>
</Grid>
)
}

正确加载第一页。然而,当我点击"显示更多"按钮时,我做onClick={() =>setSize(size+1)}, getKey函数不会得到下一个索引值,因此总是得到1。

我在这里做错了什么?

对于在google上找到这个的人,请确保if (previousPageData && !previousPageData.data) return null行是正确检查您的API的响应数据。在我的情况下,我不得不把它改成if (previousPageData && !previousPageData.data.length) return null; // reached the end

来自https://swr.vercel.app/docs/pagination#example-1-index-based-paginated-api

的示例有

if (previousPageData && !previousPageData.length) return null

而你有

if (previousPageData && !previousPageData.data) return null

这就是你所做的修改吗?

相关内容

  • 没有找到相关文章

最新更新