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

React Native好友列表无法显示用户名问题排查求助

问题排查:React Native中FriendCard无法显示用户名且好友列表展示异常

问题描述

尝试在React Native应用中展示所有好友,但FriendCard无法显示用户名。打印friendsList得到单个用户对象:

LOG {"profileImg": "https://instagram.fblr4-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.fblr4-1.fA&ccb=7-5&ig_cachccb7-5&oh=00_AfDmkQvsFt6bnAcrb4NwKah7lGmEPX5H9EXtBcumC1waJw&oe=63C9F90F&_nc_sid=cff2a4", "username": "User2"}

相关代码

Friends组件

const Friends = ({ navigation }) => { 

const [friendsList, setFriendsList] = useState([]);

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

const GetFriends = async () => {
    try {
        const loggeduser = await AsyncStorage.getItem('user');
        const loggeduserobj = JSON.parse(loggeduser);
        const res = await fetch('http://10.0.2.2:3000/friends', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ user_id: loggeduserobj.user._id })
        });
        const data = await res.json();
        setFriendsList(data.friends[0])
    } catch (error) {
        console.error(error);
    }
}

console.log(friendsList.username)
return (
    <View style={styles.container}>
        <BottomNavigation navigation={navigation} page={'friends'} />
        <TextInput placeholder="Search" style={styles.searchbar} placeholderTextColor='white'
            onChangeText={(text) => {
                setKeyword(text)
            }}
        />
        <Text style={styles.FriendsText}>Your Friends</Text>
        {
            friendsList.length !== 0 ? <FlatList
                data={friendsList}
                renderItem={({ item }) => (
                    <FriendCard key={item.username} user={item} navigation={navigation} />
                )}
            />
                :
                <Text style={styles.formHead2}>You don't have any friends</Text>
        }
    </View>
);
}

export default Friends;

FriendCard组件

const FriendCard = ({ user, navigation }) => {

return (
    <View>
        <TouchableOpacity onPress={() => navigation.navigate('userprofile', { user: user })}>
            <View style={styles.ChatCard}>
                {user.profileImg ? (
                    <Image source={{ uri: user.profileImg }} style={styles.image} />
                ) : (
                    <Image source={defaultprofileImg} style={styles.image} />
                )}
                <View style={styles.c1}>
                    <Text style={styles.username}>{user.username}</Text>
                </View>        
            </View>
        </TouchableOpacity>
    </View>
);
}

export default FriendCard

问题原因及修复方案

  • 核心问题:错误赋值单个对象给数组状态
    在GetFriends函数中,你将data.friends[0](单个用户对象)赋值给了friendsList,但friendsList初始是数组类型,且FlatList要求data必须是数组。这会导致两个问题:

    1. FlatList无法遍历单个对象,无法渲染任何FriendCard;
    2. friendsList.length !== 0判断失效(对象没有length属性,会被判定为0,一直显示“没有好友”的提示)。

    修复代码:

    // 原代码
    setFriendsList(data.friends[0])
    // 修改后
    setFriendsList(data.friends)
    
  • 辅助优化:避免未定义报错
    原代码中console.log(friendsList.username)在初始状态(空数组)时会输出undefined,可以改成console.log(friendsList[0]?.username)避免控制台报错。

  • 辅助优化:FlatList的key值更可靠
    建议用用户唯一ID(如item._id)代替item.username作为FriendCard的key,避免用户名重复导致的渲染异常:

    <FriendCard key={item._id} user={item} navigation={navigation} />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:35:26