似乎当在 GraphQL 查询中找不到值时,它将该字段设置为 null
而不是 undefined
(参见问题 here)。
null is the undefined or None of GraphQL
鉴于 React 不会为 null
值使用默认属性,处理将 GraphQL 数据传递到 React 组件的情况的最佳方法是什么。
例如,我有一个 TagList
组件,我将 GraphQL 查询的结果传递到其中。虽然我有以下内容:
TagList.defaultProps = {
tags: [],
}
如果查询没有返回任何标签,tags
的值不会是undefined
,而是null
,所以默认值不是应用,并且组件尝试使用 null
作为标签的值来呈现。
显然我可以在render方法的顶部添加一个检查并将值设置为[]
,但感觉必须有更好的解决方案。
最佳答案
GraphQL 规范不包含未定义值的概念——值只是 null 或非 null。事实上,在概述解析字段值的步骤时,它指定应将 undefined 强制转换为空值:
If result is null (or another internal value similar to null such as undefined or NaN), return null.
也就是说,在我的脑海中,有几种方法可以解决这个问题:
1.) 在客户端,创建一个可以将组件包装在其中的小型 HOC:
const UndefinedToNull = (Component) => (props) => {
const newProps = props.map(p => p === null ? undefined : p)
return <Component {...newProps}>
}
2.) 如果您使用 Apollo 作为客户端,您应该能够创建一个将 null 转换为 undefined 的中间件链接。像这样的东西:
const middlewareLink = new ApolloLink((operation, forward) => {
return forward(response).map(result => {
// transverse the result, mutating it as needed
return result
})
}
3.) 在服务器端,如果您正在使用 apollo-server
,您可以使用 formatResponse
配置选项来遍历 GraphQL 响应并转换空值或根据需要未定义。 YMMV 与其他 GraphQL 中间件。
关于javascript - 当 GraphQL 值可能为空时将其与 React 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50099092/