react-native - React Native GraphQL 嵌套数据数组返回错误
问题描述
我已经尝试了我能想到的一切来解决这个问题,但仍然很难过。我正在使用 AWS AppSync GraphQL 来存储我想调用到 SectionList 的数据集。
对于 SectionList,我使用硬编码的 id 通过 GraphQL 查询调用数据集。当我使用虚拟数据时,SectionList 会正确显示。它还正确显示 API 中的一对一关系。
我已经配置了放大以增加语句深度,并且我可以看到 Object 中的数据。
SectionList 的代码
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, Image, ImageBackground, ScrollView, TouchableOpacity, SectionList, SafeAreaView } from 'react-native';
import Feather from 'react-native-vector-icons/Feather';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { API, graphqlOperation } from 'aws-amplify';
import { getGame, listGameSections, listGames } from '../graphql/queries';
const Item = ({ title }) => (
<View>
<Text>
{title}
</Text>
</View>
);
const GameScreen = ({ navigation }) => {
const [game, setGame] = useState([]);
useEffect(() => {
const fetchGame = async () => {
const gameInfo = { id: '0e2cb273-b535-4cf7-ab16-198c44a4991c'};
if (!gameInfo) {
return;
}
try {
const response = await API.graphql(graphqlOperation(getGame, {id: gameInfo.id}))
setGame(response.data.getGame);
console.log(response);
} catch (e) {
}
};
fetchGame();
}, [])
return (
<SafeAreaView>
<View>
<Text>
{game.name}
</Text>
</View>
<SectionList
sections={game.sections.items}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<View>
<Text>{title}</Text>
</View>
)}>
</SafeAreaView>
)
};
export default GameScreen;
对象的日志。 我正在尝试显示 getGame.sections.items 数组,但返回错误 undefined is not an object。无法读取未定义的属性项。
请帮忙,我现在很困惑。当我在函数前面调用 game.name 时,它会正确显示,但是 game.sections.items 在 SectionList 中抛出一个错误,它是未定义的。
解决方案
Xadm,您为我指明了正确的方向。我将此添加到我的代码中:
const [game, setGame] = useState({});
const [gameSection, setGameSection] = useState([]);
在我的 useEffect 中:
setGameSection(response.data.getGame.sections.items)
调用数据时,game.name 需要一个对象,而 game.sections.items 需要一个用于 SectionList 的数组。为每个初始状态添加 2 个不同的函数,一个用于对象,一个用于数组,能够解决问题并呈现数据。
推荐阅读
- regex - 使用 Beautiful Soup 查找和替换
- javascript - 在 Redux 表单“字段”组件中使用 React 组件
- c++ - C++ std::future 挂起超时
- ruby-on-rails - Ruby docker 镜像无法在树莓派上安装 nodejs
- python - 如何获得 RandomForestRegressior 的 train_error
- javascript - 是否可以将 ASCII 艺术添加到 javascript 弹出窗口?
- php - PhpStorm - 所有文件都有蓝色字体(方法/属性没有颜色编码)
- python - 如何在其属性上找到具有相同函数返回值的列表中的两项?
- javascript - 使用相应的复选框 jquery 启用禁用输入文本
- javascript - React - getDerivedStateFromProps 是否需要返回所有状态属性?