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

如何在React Native的Text组件中显示数组的键与值?

React Native 遍历数组渲染对象属性报错解决办法

问题场景

你的数组结构如下:

const getExpense = [{"fecha": "09", "text": "Comida", "value": 2896}, {"fecha": "09", "text": "Misc", "value": 1714}, {"fecha": "09", "text": "Transporte", "value": 1525}, {"fecha": "09", "text": "Salida", "value": 1260}, {"fecha": "09", "text": "Deporte", "value": 560}, {"fecha": "09", "text": "Farmacia", "value": 367}, {"fecha": "09", "text": "Pulperia", "value": 126}, {"fecha": "09", "text": "Ayuda", "value": 50}]

你尝试用以下函数遍历数组渲染,但触发错误:

function display(){
        return getExpense.map((item,item1,item2)=>{
            return(
                <RN.Text>
                    {item} {item1} {item2}
                </RN.Text>
            )
        })
    }

调用代码:

return(
    <RN.View>
        <RN.Text>
              {display()}
        </RN.Text>
    </RN.View>
)

错误信息:

Render Error: Objects are not valid as a React Child (Found: an object with keys {fecha, text, value}. If you meant to render a collection of children, use an array instead.

错误原因

  1. 直接渲染item对象:React无法将对象作为子元素渲染,必须提取对象的属性值转换成文本。
  2. map参数命名错误:第二个参数是数组索引,第三个是原数组,你用item1、item2命名容易混淆,且实际不需要用到原数组。
  3. 嵌套结构不当:将多个<Text>元素嵌套在一个<Text>中,虽然React允许,但更合理的是直接将元素数组放在<View>下。

解决代码

方法一:修正display函数并调整渲染结构

function display() {
  // 遍历数组,提取每个对象的属性值渲染
  return getExpense.map((item, index) => {
    // 给每个列表项添加唯一key,避免React警告
    return (
      <RN.Text key={index} style={{ marginVertical: 4 }}>
        Fecha: {item.fecha} | Tipo: {item.text} | Valor: {item.value}
      </RN.Text>
    );
  });
}

// 渲染部分
return (
  <RN.View style={{ padding: 16 }}>
    {display()}
  </RN.View>
);

方法二:直接在渲染中写map(更简洁)

return (
  <RN.View style={{ padding: 16 }}>
    {getExpense.map((item, index) => (
      <RN.Text key={index} style={{ marginVertical: 4 }}>
        Fecha: {item.fecha} | Tipo: {item.text} | Valor: {item.value}
      </RN.Text>
    ))}
  </RN.View>
);

关键说明

  • 必须通过item.属性名的方式提取对象的具体值,将其转换为文本后再渲染。
  • 列表渲染时务必添加key属性,推荐使用数据中唯一标识(如id),示例中用index是临时方案,数据有唯一值时替换更稳妥。
  • 列表元素直接放在<View>下即可,无需嵌套在单个<Text>中,符合React Native的布局逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:20:24