You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UseSWR调用JSON API时返回undefined数据问题求助

使用SWR获取JSON API数据时data/error始终返回undefined

问题描述

我尝试使用SWR从JSON API获取数据,复制官网示例代码替换API后,访问data或error值(例如执行console.log('Data from top level: ' + data))始终返回undefined。在fetcher函数末尾添加.then(json => console.log(json))能正确打印数据,修改fetcher返回值后仍未解决,通过useEffect()监听data和error也遇到同样问题。

相关代码

初始代码

const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error, isLoading } = useSWR('https://jsonplaceholder.typicode.com/todos/1', fetcher)

修改fetcher返回值的尝试

const fetcher = (...args) => fetch(...args).then(res => res.json()).then((json) => { return json; })

使用useEffect的尝试

const fetcher = (url) => fetch(url).then(res => res.json()).then(json => console.log(json));
const { data, error } = useSWR('https://jsonplaceholder.typicode.com/todos/1', fetcher)

useEffect(() => {
  console.log(`From error:  ${error}`)
  console.log(`Data from top level: ${data}`)
}, [data, error]
)

依赖版本

"dependencies": {
    "autoprefixer": "10.4.14",
    "eslint": "8.43.0",
    "eslint-config-next": "13.4.7",
    "next": "13.4.7",
    "postcss": "8.4.24",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "swr": "^2.2.0",
    "tailwindcss": "3.3.2"
  }

解决方法

  1. 声明组件为客户端组件:在Next.js 13的App Router中,默认组件是服务器组件,SWR作为客户端钩子只能在客户端组件中使用。在组件文件顶部添加:
'use client'
  1. 确保fetcher返回数据:使用useEffect尝试中的fetcher没有返回json数据,导致SWR无法获取到值,修正后需保留返回逻辑:
const fetcher = (url) => fetch(url).then(res => res.json()).then(json => {
  console.log(json);
  return json; // 必须返回数据给SWR
})
  1. 处理加载状态:初始渲染时data会是undefined,需结合isLoading判断加载状态,避免直接访问未就绪的值:
if (isLoading) return <div>加载中...</div>
if (error) return <div>加载出错</div>
return <div>获取到的数据标题:{data.title}</div>

内容的提问来源于stack exchange,提问作者Ben Ravioli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:35:07