这很有趣。我没有收到任何错误,但是来自GraphQL API的数据没有呈现到FlatList中。我在UsersScreen中看到的只是Text组件。之前我遇到了错误,因为我的数据是对象而不是数组,但是即使将对象作为数组传递后,FlatList也无法识别数据
import { API, graphqlOperation } from 'aws-amplify'
import { Text, View, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
const listUsers = `query listUsers {
listUsers {
username
}
}`;
export default function UsersScreen() {
const [allUsers, setAllUsers] = useState([]);
listQuery = async () => {
const allUsers = await API.graphql(graphqlOperation(listUsers));
setAllUsers(allUsers);
console.log(JSON.stringify(listUsers, null, 2));
};
keyExtractor = (_item, index) => index.toString()
renderItem = ({ item }) => (
<ListItem
title={item.username}
/>
)
return(
<View>
<Text>All Users</Text>
<FlatList
keyExtractor={keyExtractor}
data={allUsers}
renderItem={renderItem}
/>
</View>
);
}
答案 0 :(得分:0)
在您的代码中,我找不到调用的listQuery
方法。您可以使用React.useEffect,其效果与componentDidMount
,componentDidUpdate
相同,
componentWillUnmount
。您可以尝试以下代码:
import React, { useState, useEffect } from 'react';
....
useEffect(() => {
listQuery();
},[allUsers]);