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

React/Gatsby调用第三方非GraphQL API时map函数报错如何解决

错误原因

map()是JavaScript数组专属方法,你接口返回的res.data.full_options是键值对结构的普通对象,不支持直接调用数组方法,所以触发该报错。

解决方法

方案1:提取对象值为数组后遍历(推荐)

使用Object.values()将full_options的所有属性值提取为数组,再调用map遍历:

exports.sourceNodes = async ({ actions }) => {
    const { createNode } = actions;

    const fetchJoinOptions = () => axios.get(`https://example.com/path/to/api`)
    const res = await fetchJoinOptions()
    console.log(res.data)

    // 修改为以下写法
    Object.values(res.data.full_options).map((option, i) => {
        // 此处写你原本的处理逻辑,option为每个配置的完整对象
    })
}

方案2:同时获取键和值

如果需要用到full_options的键(即76、97这类ID字段),可以使用Object.entries():

Object.entries(res.data.full_options).map(([optionKey, option], i) => {
    // optionKey为键值,option为对应配置对象
})

低版本兼容方案

如果运行环境不支持ES6+方法,可以使用for in遍历:

for (let key in res.data.full_options) {
    if (res.data.full_options.hasOwnProperty(key)) {
        const option = res.data.full_options[key]
        // 处理逻辑
    }
}

内容的提问来源于stack exchange,提问作者Charles Langley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:06:03