【问题标题】:Dealing with null data from Apollo GraphQL处理来自 Apollo GraphQL 的空数据
【发布时间】:2020-08-04 19:43:31
【问题描述】:

只是想知道处理空数据的最佳方法是什么,在此处作为变量传递给 {useQuery}。目前,每当 categoryId 为空时,我都会收到错误“TypeError:无法读取未定义的属性‘节点’”。我没有包含我的 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>
)

}

【问题讨论】:

    标签: javascript reactjs graphql apollo


    【解决方案1】:

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

    【讨论】:

    • 好的,谢谢。您能告诉我如何有条件地返回“不存在相关标题”之类的语句,而不是引发错误吗?
    • 您可以使用skip 参数跳过查询,例如:skip: !categories.edges.length。然后,您可以使用相同的条件有条件地呈现任何替代 UI。只要确保你也修复了你的变量:categoryId: categories.edges.length &amp;&amp; categories.edges[0].node.databaseId
    猜你喜欢
    • 1970-01-01
    • 2017-06-23
    • 2021-01-21
    • 2018-05-02
    • 2014-05-27
    • 1970-01-01
    • 2020-01-24
    • 2019-06-20
    • 2021-10-12
    相关资源
    最近更新 更多