所以我试图从dynamoDB。我正在使用一个GraphQL API访问我的数据库。在提供的代码的注释部分中,我提到我已经尝试过users[1].friends.map
,它确实返回正确的朋友列表数组,但用户似乎直到朋友列表渲染后才被设置。我应该如何设置我的代码,以便在第一次呈现页面时而不是在更新页面后呈现正确的朋友列表(在用户中找到)?
const FriendsList = [
{
name: 'Name 1',
},
{
name: 'Name 2',
},
{
name: 'Name 3',
},
{
name: 'Name 4',
},
{
name: 'Name 5',
},
{
name: 'Name 6',
},
];
const Friends = (props) => {
const [refreshing, setRefreshing] = React.useState(false);
const [users, setUsers] = React.useState([]);
const [formData, setFormData] = React.useState(initialFormState);
React.useEffect(() => {
fetchUserData();
}, []);
async function fetchUserData() {
const userData = await API.graphql({ query: listUsers });
setUsers(userData.data.listUsers.items);
}
//console.log(users);
const renderFriendsList = (props) => {
/*
*Here I want to have something like...
* return users[1].friends.map((item, i) => {
* so I can iterate through the friends list
*/
return FriendsList.map ((item, i) => {
return (
<View style={{ paddingLeft: scale(10), paddingRight: scale(10) }}>
<View
style={{
backgroundColor: '#d1cfcf',
width: scale(330),
height: scale(85),
borderRadius: scale(10),
flexDirection: 'row',
borderColor: '#8f8a8a',
borderBottomWidth: 1,
}}>
<View>
<Text style={{ fontSize: 15 }}>{item.name}</Text>
</View>
</View>
</View>
);
});
};
return (
<View style={{}}>
<View style={{ marginTop: scale(5) }}>
{renderFriendsList()}
</View>
</View>
);
}
fetchUserData()
应该设置users
用户数据,但是当我打电话给用户时before第一次渲染时,用户仍然是未定义的。如果应用程序正在运行并且已从friendsList呈现好友列表,然后我将其更改为用户1 https://i.stack.imgur.com/dEWY6.png.friends 即时运行,它可以工作,但这显然是一个问题,因为它第一次无法正确渲染。我用React.useEffect()
我想这会打电话给fetchUserData()
当页面呈现时。
Here is the output I am getting when I console.log(users.result)