首页 > 解决方案 > 在 Next.js 中使用 getServerSideProps 和 useEffect 获取数据会导致重复请求

问题描述

getServerSideProps 用来获取这样的初始文章数据:

export const getServerSideProps = async () => {
  const url =
    "https://conduit.productionready.io/api/articles?limit=10&offset=0";
  const res = await fetch(url);
  const resJson = await res.json();

  return {
    props: {
      data: resJson.articles
    }
  };
};

我需要在页面更改时更新文章,所以我有以下代码:

export default function IndexPage(props) {
  const { data } = props;
  const [articles, setArticles] = useState(data);
  const [page, setPage] = useState(0);

  useEffect(() => {
    const fetchData = async (page) => {
      const url = `https://conduit.productionready.io/api/articles?limit=10&offset=${page}`;
      const res = await fetch(url);
      const resJson = await res.json();
      setArticles(resJson.articles);
    };

    fetchData(page);
  }, [page]);

  //....
}

那么问题来了:

  1. 当您直接请求此页面时, getServerSideProps 将在服务器端运行并获取文章。但是在客户端, fetchDatain theuseEffects也会运行再次获取相同的文章,这是多余的并且有点重复。
  2. 通过客户端路由从另一个页面跳转到IndexPage的时候,同样的文章数据也有两个请求:一个请求发送到getServerSideProps服务器端运行,另一个请求发送 fetchData。同样,对相同数据的冗余请求。

完整的演示在这里

我认为这不是一个不寻常的情况。我已经搜索了很多,但不幸的是,我还没有找到任何合适的解决方案。有没有人遇到同样的情况或知道处理它的最佳做法?

标签: reactjsnext.js

解决方案


推荐阅读