我使用 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]);
//....
}
那么问题来了:
getServerSideProps
在服务器端运行并获取文章。但是在客户端,fetchData
中的 useEffects
也会再次运行以获取相同的文章,这是多余的并且有点重复。IndexPage
时,对于相同的文章数据也有两个请求:一个请求被发送到服务器端运行 getServerSideProps
,另一个请求由fetchData
发送。同样,对相同数据的冗余请求。完整的演示是here
我认为这不是一个不寻常的情况。我搜索了很多,但不幸的是,我还没有找到任何合适的解决方案。有没有人遇到同样的情况或知道处理它的最佳做法?