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

React Native:如何渲染Fetch获取的非原生类型数据

解决React Native "Objects are not valid react child" 错误

这个错误的核心是你试图让React渲染一个对象,而不是它能识别的可渲染元素(字符串、数字、React组件等)。结合你的代码,问题出在以下两个可能的地方,对应解决方案如下:

1. 确认后端返回的gleam.bodyText类型

从后端获取的gleam.bodyText可能不是字符串,而是嵌套对象。先添加调试日志确认数据结构:

useEffect(() => {
  fetch('http://192.168.1.17:8080/getActualGleams')
    .then((response) => response.json())
    .then((json) => {
      // 打印数据,排查bodyText的类型
      console.log('Gleam数据:', json);
      json.forEach(item => console.log('bodyText详情:', typeof item.bodyText, item.bodyText));
      setGleamData(json);
    })
    .catch((error) => console.error(error))
    .finally(() => setLoading(false));
}, []);

如果发现bodyText是对象,提取它的可渲染字段(比如假设存在content字段):

{gleamData.map(gleam => <Gleam key={gleam.headerText}>{gleam.bodyText.content}</Gleam>)}

临时调试可以把对象转成JSON字符串:

{gleamData.map(gleam => <Gleam key={gleam.headerText}>{JSON.stringify(gleam.bodyText)}</Gleam>)}

2. 检查自定义组件Gleam的实现

你的Gleam组件可能没有正确处理传入的children,确保它显式渲染props.children:

// ../Elements/Gleam.js
import { View, Text, StyleSheet } from 'react-native';

export default function Gleam(props) {
  return (
    <View style={styles.container}>
      {/* 必须显式渲染传入的children */}
      <Text>{props.children}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  }
});

如果Gleam期望通过props接收数据,修改调用方式:

{gleamData.map(gleam => (
  <Gleam 
    key={gleam.headerText} 
    bodyText={gleam.bodyText} 
  />
))}

然后在Gleam里处理props:

export default function Gleam({ bodyText }) {
  // 处理对象类型的bodyText
  const displayText = typeof bodyText === 'object' ? JSON.stringify(bodyText) : bodyText;
  return (
    <View style={styles.container}>
      <Text>{displayText}</Text>
    </View>
  );
}

3. FlatList的正确使用(补充方案)

如果想用FlatList,确保renderItem里的内容是可渲染的:

{isLoading ? <Text>Loading...</Text> :
  <FlatList
    data={gleamData}
    keyExtractor={(item) => item.headerText}
    renderItem={({ item }) => (
      <Gleam bodyText={typeof item.bodyText === 'object' ? item.bodyText.content : item.bodyText} />
    )}
  />
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:56:07