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

React Native中如何正确引用API返回的JSON数据并渲染User组件?

问题分析与修正方案

你的代码存在的核心问题:

  • State 类型错误:users 初始化为对象 {},但 FlatList 的 data 属性要求传入数组类型,导致渲染逻辑完全失效。
  • API 地址错误:https://randomuser.me/api/users/ 不是合法接口地址,正确的单用户请求地址是 https://randomuser.me/api/(默认返回1条用户数据)。
  • 用户追加逻辑错误:初始加载和点击按钮时,你用新请求的数据直接覆盖了原有 users 状态,而非将新用户追加到列表中。
  • 语法错误:按钮的 onPress 回调里多余了 , [],这是 useEffect 的依赖数组写法,此处完全不需要。
  • 缺少容错处理:未处理数据未加载时的属性访问报错,也没有空状态提示。

正确的引用方式与修正代码:

randomuser.me 返回的结构是 { results: [用户对象] },所以单个用户数据在 item.results[0] 下,搭配可选链 ?. 可避免未加载时的报错。以下是修正后的完整代码:

import { Text, View, Button, FlatList } from 'react-native';
import { useEffect, useState } from 'react';

const API = 'https://randomuser.me/api/';

const User = (props) => (
  <View style={{ marginVertical: 8, padding: 8, borderWidth: 1, borderColor: '#ccc' }}>
    <Text>Name: {props.fname} {props.lname}</Text>
    <Text>Country: {props.country}</Text>
  </View>
);

const renderUser = ({ item }) => (
  <User 
    fname={item.results[0]?.name.first} 
    lname={item.results[0]?.name.last} 
    country={item.results[0]?.location.country}
  />
);

export default function App() {
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const fetchUser = () => {
    setIsLoading(true);
    fetch(API)
      .then((response) => response.json())
      .then((json) => {
        // 追加新用户到数组,而非覆盖
        setUsers(prevUsers => [...prevUsers, json]);
      })
      .catch((error) => console.error('请求失败:', error))
      .finally(() => setIsLoading(false));
  };

  useEffect(() => {
    fetchUser();
  }, []);

  return (
    <View style={{ flex: 1, padding: 16 }}>
      <Button 
        title={isLoading ? "加载中..." : "添加用户"} 
        onPress={fetchUser}
        disabled={isLoading}
      />

      {/* 空状态提示 */}
      {users.length === 0 && !isLoading && (
        <Text style={{ marginTop: 20, textAlign: 'center' }}>暂无用户,点击按钮添加!</Text>
      )}

      <FlatList 
        data={users} 
        renderItem={renderUser}
        keyExtractor={(item, index) => index.toString()}
        style={{ marginTop: 16 }}
      />
    </View>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:39:59