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

React Native SectionList如何适配API返回的嵌套items数据?

React Native SectionList 适配API返回数据的解决方法

SectionList 要求每个 section 的 data 字段是直接的数组类型,而你的API返回的 data 是包含 items 数组的对象,只需把数据转换成符合要求的格式即可解决问题,以下是两种可行方案:

方案一:预处理API数据(推荐)

在将数据传入 SectionList 前,遍历API返回的数组,把每个 section 里的 data 替换为 data.items:

// API返回的原始数据
const apiResponseData = [
    {
        date: "Main dishes",
        data: { 
                items: ["Pizza", "Burger", "Risotto"]
            },
    },
    {
        date: "Sides",
        data: { 
                items: ["French Fries", "Onion Rings", "Fried Shrimps"]
            },
    },
];

// 转换为SectionList兼容格式
const sectionListData = apiResponseData.map(section => ({
    ...section,
    data: section.data?.items || [] // 加入容错处理,避免空值报错
}));

之后直接将 sectionListData 作为 SectionList 的 sections 属性传入即可正常渲染。

方案二:自定义SectionList的数据源映射(不推荐)

如果不想修改原始数据,可以在 SectionList 的相关属性中直接指定数据来源,但这种方式会增加代码复杂度:

<SectionList
    sections={apiResponseData}
    renderItem={({ item }) => <Text>{item}</Text>}
    // 重写getItem方法,指定从items数组取数据
    getItem={(data, index) => data.items[index]}
    // 重写getItemCount方法,返回items数组长度
    getItemCount={(data) => data.items?.length || 0}
    renderSectionHeader={({ section }) => <Text>{section.date}</Text>}
/>

这种方式虽然不用修改原始数据,但需要额外配置 getItem 和 getItemCount,代码可读性和维护性不如方案一,因此更推荐使用数据预处理的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:35:24