首页 > 解决方案 > 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 中抛出一个错误,它是未定义的。

标签: react-nativegraphqlaws-amplifyreact-native-flatlistreact-native-sectionlist

解决方案


Xadm,您为我指明了正确的方向。我将此添加到我的代码中:

const [game, setGame] = useState({});
const [gameSection, setGameSection] = useState([]);

在我的 useEffect 中:

setGameSection(response.data.getGame.sections.items)

调用数据时,game.name 需要一个对象,而 game.sections.items 需要一个用于 SectionList 的数组。为每个初始状态添加 2 个不同的函数,一个用于对象,一个用于数组,能够解决问题并呈现数据。


推荐阅读