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

调用DummyJSON API时出现TypeError: res is undefined问题求助

问题原因及解决办法

核心问题1:API函数丢失返回数据

你的getAllProducts函数里,最后一个.then(console.log)只会打印数据,但不会返回数据——console.log的返回值是undefined,所以这个Promise最终传给组件的就是undefined,这就是你拿到res is undefined的原因。

核心问题2:数据字段取值错误

DummyJSON的/products接口返回的结构里,产品列表是在products字段下,不是data,所以就算拿到数据,res.data也会是undefined。


修改后的API请求代码

export const getAllProducts = () => {
    return (
        fetch('https://dummyjson.com/products')
            .then(res => res.json())
            .then(data => {
                console.log(data); // 保留打印
                return data; // 必须把数据返回给后续的Promise链
            })
    )
}

修改后的Products组件关键代码

useEffect(() => {
    getAllProducts()
        .then((res) => {
            setItems(res.products); // 改成products字段
        })
        .catch(err => {
            console.log(err)
        })
}, []);

这样修改后,就能正确获取并渲染产品数据了。

内容的提问来源于stack exchange,提问作者mutebi godfrey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:50:00