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

React Native SectionList获取数据后标题显示[object Object]问题求助

解决React Native SectionList标题显示[object Object]的问题

问题根源

SectionList渲染标题时出现[object Object],本质是你传入的sections数组格式不符合要求——要么每个section对象的title字段被设置成了对象类型而非字符串,要么你直接把原始API数据当成sections传入,没有按分类转换结构。

解决步骤

1. 确认API数据结构

先明确你的API返回数据里,每个条目都包含用于分类的字段(比如category),例如:

// API返回的原始数据示例
const apiData = [
  { id: 1, name: '宫保鸡丁', category: '热菜' },
  { id: 2, name: '拍黄瓜', category: '凉菜' },
  { id: 3, name: '鱼香肉丝', category: '热菜' },
];

2. 把原始数据转换为SectionList要求的格式

SectionList需要的sections数组,每个元素必须包含title(分类名称,字符串类型)和data(该分类下的所有条目数组)。你可以手动实现分组逻辑,或者用工具库简化:

手动分组实现:

// 自定义分组函数
const groupByCategory = (data) => {
  const grouped = {};
  data.forEach(item => {
    const category = item.category;
    if (!grouped[category]) {
      grouped[category] = [];
    }
    grouped[category].push(item);
  });
  // 转换为SectionList需要的sections格式
  return Object.keys(grouped).map(title => ({
    title,
    data: grouped[title]
  }));
};

// 请求API后处理数据
const fetchData = async () => {
  const response = await fetch('你的API地址');
  const rawData = await response.json();
  const sections = groupByCategory(rawData);
  this.setState({ sections }); // 把转换后的sections存入state
};

用lodash简化分组:

import _ from 'lodash';

const fetchData = async () => {
  const response = await fetch('你的API地址');
  const rawData = await response.json();
  const grouped = _.groupBy(rawData, 'category');
  const sections = Object.entries(grouped).map(([title, data]) => ({ title, data }));
  this.setState({ sections });
};

3. 修正renderSectionHeader渲染逻辑

确保你在renderSectionHeader中正确访问section的title字段,而不是整个section对象:

renderSectionHeader = ({ section }) => (
  <View style={{ padding: 10, backgroundColor: '#f5f5f5' }}>
    <Text style={{ fontSize: 16, fontWeight: 'bold' }}>{section.title}</Text>
  </View>
);

关键注意点

  • 绝对不要直接把API返回的原始数组赋值给SectionList的sections属性,必须先按分类转换结构。
  • 若API返回的分类是嵌套对象(比如category: { name: '热菜' }),则要取category.name作为section的title,避免传入对象导致渲染出[object Object]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:05:03