我试图在我的应用程序中显示所有朋友,但当我尝试这样做时,它不显示朋友卡中的用户名,当我尝试记录frienlist时,它会记录类似这样的内容,我如何才能修复这个问题,并在每个朋友卡中显示所有朋友?我的代码有什么问题?
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"}
文件:
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;
好友卡:
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
1条答案
按热度按时间gab6jxml1#
Flatlist呈现数据列表,但您在State变量中设置对象,只需将setFriendsList(data.friends[0])更改为setFriendsList(data.friends)即可解决您的问题。