1

我正在使用带有 SWR 的 NextJS 来获取数据。我用返回的 initialData 提供 SWR getServerSideProps

分页工作得很好。当我转到第 3 页时,我会看到第 3 页的数据。当我转到第 5 页时,我首先再次看到第 1 页,然后再看到第 5 页数据。我认为这是在验证期间发生的。我想在第 5 页准备好之前显示第 3 页数据。我该如何解决这个问题?

我的取号器

const fetcher = url => axios.get(url).then(res => res.data)

我如何获取数据getServerSideProps

export const getServerSideProps = async() => {
    const pages = await fetcher('http://127.0.0.1:8000/api/pages/')

    return { props: { pages } }
}

我在哪里调用 SWR 并渲染结果

function Page ({ pageIndex, props }) {
const { data, error } = useSWR(`http://127.0.0.1:8000/api/pages/?page=${pageIndex}`, fetcher, {dedupingInterval: 15000, initialData: props.pages, revalidateOnFocus: false});
return (
        {data.results.map(page => <p>page</p>)}
    )

}

我如何称呼页面和分页

export default function Pages(props) {
...
const [pageIndex, setPageIndex] = useState(1);
<Page pageIndex={pageIndex} props={props}/>
<Pagination pages={props.genes.total_pages} setPageIndex={setPageIndex}/>
...
}
4

1 回答 1

2

我已经按照GitHub postuseRef中的建议使用解决了。

更新页面功能

function Page ({ pageIndex, props }) {
const mutableRef = useRef();
const { data, error } = useSWR(`http://127.0.0.1:8000/api/pages/?page=${pageIndex}`, fetcher, {dedupingInterval: 15000, initialData: mutableRef.current ? mutableRef.current : props.pages, revalidateOnFocus: false});

if (data !== undefined && mutableRef) {
    mutableRef.current = data;
  }

return (
        {data.results.map(page => <p>page</p>)}
    )

}
于 2021-08-14T06:44:59.690 回答