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

React调用后端API返回的JSON数组执行map操作报错如何解决?

问题根因
  • 全局状态初始值里singleGame被设置为空对象{},组件首次渲染时后端API请求还未完成,此时从singleGame中解构出来的platforms、developer、composer等数组字段为undefined,直接调用map方法会触发类型错误。
  • useEffect逻辑存在时序问题:你在同一个useEffect中同步调用异步的fetchSingleGame方法后,立即读取singleGame的值,此时请求尚未返回,读取到的还是初始空对象的值,会导致标题设置等逻辑也出现异常。
修复方案

1. 增加加载态拦截

你的全局状态中已经内置了loading字段,在页面组件中优先判断加载状态,未加载完成时不渲染业务内容,避免读取到未初始化的字段:

// 先从全局上下文取出loading状态
const { singleGame, fetchSingleGame, loading } = useGlobalContext();

// 组件最前面加加载态判断
if (loading) {
  return <div>加载中...</div>
}

2. 给解构字段设置默认值

解构singleGame的字段时,给所有可能为空的字段设置兜底默认值,避免字段为undefined:

const {
  name = '',
  poster = '',
  composer = [],
  developer = [],
  remastered = false,
  synopsis = '',
  ESRB_rating = '',
  platforms = [],
  engine = '',
  release_date = '',
  genre = '',
  publisher = '',
  trailer = '',
  website = '',
} = singleGame;

3. 数组调用map前加判断

调用map方法前用可选链运算符做容错,同时给遍历生成的元素添加唯一key属性避免React警告:

{platforms?.map((pla, idx) => {
  return <span key={idx} className='text-light'>{pla}&nbsp;</span>;
})}

4. 拆分useEffect逻辑

把数据拉取和数据更新后的副作用逻辑拆分到不同的useEffect中,避免时序问题:

// 只负责拉取单游戏数据,依赖项为id
useEffect(() => {
  fetchSingleGame(id);
}, [id, fetchSingleGame]);

// 只负责在数据更新后修改标题和当前状态,依赖项为单游戏名称
useEffect(() => {
  if (!singleGame.name) return;
  let title = 'Games';
  document.title = `${title} | ${singleGame.name}`;
  setCurrent(title.toLowerCase());
  setGameCurrent(singleGame.name);
}, [singleGame.name, setCurrent, setGameCurrent]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:36:03