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

React Native中FlatList无法渲染数据问题求助

问题分析与解决

核心问题1:未更新状态导致FlatList无数据

你的代码里没有把接口返回的数据存入allFriends状态,useState初始值是空数组,后续也没调用setAllFriends更新,所以FlatList的data一直是空的,自然不会渲染任何内容。

核心问题2:res.data.fullName undefined的原因

你直接访问res.data.fullName但返回undefined,说明接口返回的res.data不是单个用户对象,而是用户数组,fullName应该在数组的每个元素里。


修改后的代码

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

const FriendsList = () => {
    const [allFriends, setAllFriends] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:3000/api/users')
            .then(res => {
                // 确认接口返回的是数组,存入状态
                console.log('接口返回数据:', res.data);
                setAllFriends(res.data);
            })
            .catch(err => console.log(err))
    }, [])

    return (
        <>
            <Text>Friends:</Text>
            <FlatList
                data={allFriends}
                // 用item的唯一ID作为key,避免索引带来的性能问题
                keyExtractor={(item) => item.id.toString()}
                renderItem={({ item }) => {
                    // 先打印item确认字段名是否正确
                    console.log('当前渲染的item:', item);
                    return ( 
                        <View style={{ padding: 10 }}>   
                            <Text>{item.fullName || '无姓名'}</Text>
                        </View>
                    )
                }}
            />
        </>
    )
}

export default FriendsList

额外检查点

  • 打开控制台看接口返回数据的打印结果,确认每个元素里的字段名是不是fullName,如果是full_name或者name,要对应修改item.fullName为正确的字段名。
  • 确保接口返回的数组里每个元素都有唯一的id字段,如果没有,也可以用item.fullName(但要保证姓名不重复),或者暂时用索引,但不推荐长期使用索引作为key。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:18