reactjs - 在 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]);
//....
}
那么问题来了:
- 当您直接请求此页面时,
getServerSideProps
将在服务器端运行并获取文章。但是在客户端,fetchData
in theuseEffects
也会运行再次获取相同的文章,这是多余的并且有点重复。 - 通过客户端路由从另一个页面跳转到
IndexPage
的时候,同样的文章数据也有两个请求:一个请求发送到getServerSideProps
服务器端运行,另一个请求发送fetchData
。同样,对相同数据的冗余请求。
完整的演示在这里
我认为这不是一个不寻常的情况。我已经搜索了很多,但不幸的是,我还没有找到任何合适的解决方案。有没有人遇到同样的情况或知道处理它的最佳做法?
解决方案
推荐阅读
- jquery - 获取壁橱的价值select2 jquery
- amazon-dynamodb - DynamoDB Keys - 一个高基数一个低基数?
- angular - 从 API 接收“应用程序/八位字节流”时 JSON 中出现意外令牌
- angular - Angular 5 - httpClient 未按请求发送标头
- algorithm - 使用重复值编码排列
- entity-framework - 自定义实体框架核心迁移脚本?
- java - androidGradle 构建失败任务':app:processDebugResources'的执行失败
- javascript - 使用 WebAudio 的时钟来安排 Cordova 的功能
- r - 数据整理帮助:用所有数据拆分一列
- python - Scrapy-Drop 管道中的项目字段?