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

ReactJS数组映射无内容显示问题求助

问题分析与解决方案

问题原因

你当前的listCategory是二维数组(每个元素都是features数组),而渲染时直接尝试访问数组的category属性——数组本身没有这个属性,所以页面无内容显示。

从控制台输出能看到:

  • res[1].map(item => item.data.features)返回的是数组套数组的结构
  • res[1].map(item => item.data.features[0])才是包含category字段的单个对象

解决方案

根据你的数据结构,分两种场景处理:

场景1:每个features数组只有1个元素

直接提取每个features里的第一个对象,把listCategory转成一维对象数组:

const getListCategoryPoi = () => {
    setIsLoading(true);
    getCategoryPoi()
      .then((res) => {
        // 修改这里,取features的第一个元素
        setListCategory(res[1].map((item) => item.data.features[0]));
      })
      .catch((reject) => {
        console.log(reject);
      })
      .finally(() => setIsLoading(false));
};

场景2:每个features数组有多个元素

需要把二维数组扁平化,合并成包含所有对象的一维数组:

const getListCategoryPoi = () => {
    setIsLoading(true);
    getCategoryPoi()
      .then((res) => {
        // 用flat()扁平化二维数组,或用reduce拼接
        const flatFeatures = res[1].map((item) => item.data.features).flat();
        // 或者用reduce:const flatFeatures = res[1].reduce((acc, item) => [...acc, ...item.data.features], []);
        setListCategory(flatFeatures);
      })
      .catch((reject) => {
        console.log(reject);
      })
      .finally(() => setIsLoading(false));
};

渲染代码保持不变

修改数据后,原来的渲染逻辑就能正常显示category字段:

{listCategory.map((item, index) => (
  <p key={index}>{item.category}</p>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:10:23