Next.js中使用useSWR时data始终为undefined的问题求助
问题排查与解决
你的代码核心问题出在fetcher函数上——它没有返回异步请求的Promise,导致useSWR无法获取到API返回的数据,始终处于加载状态。
修正后的代码
修复fetcher函数
在fetch调用前加上return,让函数返回Promise对象:
import useSWR from "swr"; const apiUrl = process.env.NEXT_PUBLIC_API_URL; // 修复:添加return返回Promise const fetcher = (url) => { return fetch(url).then((res) => res.json()); }; // 或者用更简洁的箭头函数写法 // const fetcher = (url) => fetch(url).then(res => res.json()); export default function useSocialMedia() { const url = apiUrl + "/socialMedia"; const { data, error } = useSWR(url, fetcher); console.log("data : ", data); return { socialMedia: data, loading: !error && !data, error: error, }; }
额外检查项
- 确认
NEXT_PUBLIC_API_URL环境变量已正确配置,拼接后的完整URL(比如apiUrl + "/socialMedia")能在浏览器中正常访问,返回合法的JSON数据。 - 检查API是否存在跨域(CORS)问题,若存在需在后端配置允许当前域名的跨域请求。
- 可在
fetcher中添加响应状态校验,提前捕获请求错误:const fetcher = (url) => { return fetch(url) .then((res) => { if (!res.ok) throw new Error('请求失败'); return res.json(); }); };
内容的提问来源于stack exchange,提问作者Fabien Delmotte
相关产品推荐
相关产品推荐

