处理来自 Apollo GraphQL 的空数据

Dealing with null data from Apollo GraphQL

只是想知道处理空数据的最佳方法是什么,它作为变量传递给这里的 {useQuery}。目前,每当 categoryId 为 null 时,我都会收到错误 "TypeError: Cannot read property 'node' of undefined"。我没有包括我的 graphQL 查询,因为它可能没有必要。提前致谢。

const RelatedContent = ({categories}) => {

const {data, loading, error} = useQuery(GET_TITLES_BY_CATEGORY, {
    variables: {
        categoryId: categories.edges[0].node.databaseId
    },
    fetchPolicy: 'no-cache'
})

if (loading) return <div>Loading...</div>

if (error) return `Error! ${error.message}`

return (
    <div className={styles.sectionBackground + " section"}>
        <div className="container">
            <h3 className={styles.title}>Related film and TV</h3>
            <div className="columns is-multiline is-mobile">
                {
                    data.impactArticles.edges.map((item) => {
                        return (
                            <div className="column">
                                <ContentCard 
                                    item={item}
                                />
                            </div>
                        )
                    })
                }
            </div>
        </div>
    </div>
)

}

错误显示为 "Cannot read property 'node' of undefined",因此您正试图访问未定义值的 属性。在这种情况下,它将是 categories.edges[0]。如果您有一个空数组,访问该数组中的第一个元素将导致值 undefined。换句话说,您假设 edges 总是至少有一个元素,但事实并非如此。所以你的代码需要反映这个事实。您如何处理(跳过查询、传递其他变量等)完全取决于您的业务需求,因此我们无法为您解答。