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

iOS背景React Native新手求助SectionList数据结构报错问题

解决React Native SectionList的"TypeError: undefined is not an object (evaluating 'section.data.length')"错误

嘿,作为有iOS开发背景的React Native新手,你遇到的这个问题其实是SectionList组件的核心要求没搞清楚——它强制每个section对象必须包含data字段,这个字段是该分组下要渲染的子项数组。你新换的JSON数据里,每个section直接把属性放在了根层级,没有data数组,组件找不到section.data,自然就抛出了这个错误。

下面给你两种可行的解决方案:

方案一:改造数据源(推荐,符合SectionList设计规范)

直接给每个section添加data字段,把当前的单条数据包装成数组(哪怕每个分组只有一个子项)。修改后的JSON应该是这样:

[
  {
    "key": "New",
    "data": [
      {
        "gender": "male",
        "name": {"title":"mr","first":"janique","last":"costa"},
        "registered":"2014-09-22 22:38:28",
        "phone":"(48) 4518-1459",
        "cell":"(22) 3632-3660"
      }
    ]
  },
  {
    "key": "New11111",
    "data": [
      {
        "gender": "male11111",
        "name": {"title":"mr11111","first":"janique11111","last":"costa11111"},
        "registered":"2014-09-22 22:38:2811111",
        "phone":"(48) 4518-145911111",
        "cell":"(22) 3632-366011111"
      }
    ]
  }
]

之后调整你的_renderItem方法,就能正常获取gender字段了:

_renderItem = ({ item, section }) => (<Text>{item.gender}</Text>)

方案二:动态处理数据(无需修改原始数据源)

如果不想改动原始JSON,你可以在传递给SectionList前,给每个section动态添加data字段:

render() {
  // 把每个section自身包装成data数组
  const processedSections = data.map(section => ({
    ...section,
    data: [section]
  }));
  
  return (
    <View style={styles.container}>
      <SectionList 
        sections={processedSections} 
        // 此时item就是原来的section对象,直接访问gender即可
        renderItem={({ item }) => (<Text>{item.gender}</Text>)} 
        renderSectionHeader={this._renderSectionHeader} 
      />
    </View>
  );
}

补充一句:SectionList的设计初衷就是展示"分组-子项"结构的列表,如果未来你的每个分组会有多个子项,方案一更贴合组件的设计逻辑,维护起来也更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:48:52