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

Next.js调用CoinGecko API后子组件执行map报map is not a function错误求助

问题根因

  • 请求URL存在非法换行:你在getServerSideProps中定义的CoinGecko接口地址包含手动换行,模板字符串会保留换行符,导致实际请求的路径携带%0A转义字符,接口无法识别路径返回错误响应对象,而非预期的加密货币数组,对象不存在map方法因此抛出报错。
  • 缺少类型校验逻辑:未对接口返回值、组件入参做数组类型校验,异常场景下直接调用数组方法直接触发报错。

修复方案

1. 修复接口请求逻辑

调整getServerSideProps代码,删除URL内的换行,新增请求错误捕获和返回值类型校验,确保传递给组件的参数始终是数组:

export const getServerSideProps = async () => {
  try {
    // 移除URL内所有换行,保证路径合法
    const res = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=50&page=1&sparkline=false");
    if (!res.ok) throw new Error('接口请求异常')
    const filteredCoins = await res.json();
    return {
      props: {
        // 校验返回值类型,非数组场景用空数组兜底
        filteredCoins: Array.isArray(filteredCoins) ? filteredCoins : []
      }
    };
  } catch (err) {
    // 请求失败时返回空数组,避免组件崩溃
    return {
      props: {
        filteredCoins: []
      }
    }
  }
};

2. 新增组件入参防御判断

调整CoinList组件代码,新增数组类型校验,空数据场景展示兜底内容:

import Coins from './Coins';

export default function CoinList({filteredCoins}) {
  // 非数组/空数组场景展示兜底提示
  if (!Array.isArray(filteredCoins) || filteredCoins.length === 0) {
    return <p>暂无相关加密货币数据</p>
  }
  return filteredCoins.map(coin => {
    return (
      <Coins
        key={coin.id}
        name={coin.name}
        id={coin.id}
        price={coin.current_price}
        symbol={coin.symbol}
        marketcap={coin.total_volume}
        volume={coin.market_cap}
        image={coin.image}
        priceChange={coin.price_change_percentage_24h}
      />
    );
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:06:07