javascript - 当 GraphQL 值可能为空时将其与 React 一起使用

标签 javascript reactjs graphql default-value react-proptypes

似乎当在 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/

相关文章:

reactjs - 如何在样式组件中使用 {withTheme}。?任何人请给出实时示例

graphql - 如何在graphql突变中设置多对多关系?

wordpress - 带有 wordpress 的 Gatsby 找不到未使用的 ACF 灵活内容字段

python - 使循环依赖模型属性在 graphene-django 中可查询

javascript - Angular 2 *ngIf 为 'this'

javascript - 访问 Prime UI 在自动完成中选择的项目 (pui-autocomplete)

javascript - 当我更改组件时,如何重新定义 reducer 的初始状态

javascript - 隐藏 Resco Mobile CRM 中的选项

javascript - svg - 绘制空心矩形(矩形 donut )?

javascript - React-Native 不使用导航器传递 props?