useSWRInfinite - getKey 函数始终将 pageIndex 获取为 1

Mop*_*ath 2 javascript reactjs swr

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

我的代码如下...

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>
  )
}
Run Code Online (Sandbox Code Playgroud)

它正确加载第一页。但是,当我单击“显示更多”按钮(其中执行 onClick={() => setSize(size+1)})时,getKey 函数不会获取下一个索引值,因此始终获取 1。

我在这里做错了什么?

小智 5

对于在 google 上找到此内容的人,请确保该 if (previousPageData && !previousPageData.data) return null 行正确检查您的 API 的响应数据。就我而言,我必须将其更改为 if (previousPageData && !previousPageData.data.length) return null; // reached the end