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

React Native中如何展示API请求获取的单个数据对象

问题原因

FlatList 组件的 data 属性要求必须传入数组类型的值,你当前传入的是单个对象,不符合组件要求,所以不会渲染任何内容。

解决方案

方案1:仍使用FlatList(不推荐)

只需要把你的单个用户对象包裹成长度为1的数组即可:

<FlatList
  data={[getProfileApi.data]}
  keyExtractor={item => item.id.toString()}
  renderItem={({ item }) => (
    <Text>{item.email}</Text>
  )}
/>

方案2:直接渲染(推荐)

单个对象完全不需要使用列表组件,直接读取对象字段渲染即可,写法更简单,性能也更优:

注意要加非空判断,避免接口请求完成前访问字段引发报错

const ProfilePage = () => {
  // 请将变量替换为你实际的接口返回变量
  if (!getProfileApi.data) {
    return <Text>数据加载中...</Text>
  }
  const userInfo = getProfileApi.data
  return (
    <View>
      <Text>用户ID:{userInfo.id}</Text>
      <Text>邮箱:{userInfo.email}</Text>
      <Text>姓名:{userInfo.first_name} {userInfo.last_name}</Text>
      <Text>性别:{userInfo.gender}</Text>
      <Text>用户类型:{userInfo.user_type}</Text>
      <Text>出生日期:{userInfo.profile.dob}</Text>
      {/* 头像渲染示例 */}
      <Image
        source={{ uri: userInfo.profile.profile_pic }}
        style={{ width: 100, height: 100, borderRadius: 50 }}
      />
      {/* 空值字段可加判断后按需展示 */}
      {userInfo.profile.address && <Text>地址:{userInfo.profile.address}</Text>}
    </View>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:24:05