【问题标题】:Using GraphQL values with React When They Might Be null当 GraphQL 值可能为 null 时与 React 一起使用
【发布时间】:2018-10-10 11:09:37
【问题描述】:

似乎当在 GraphQL 查询中找不到值时,它会将该字段设置为 null 而不是 undefined(参见问题 here)。

null 是 GraphQL 的 undefined 或 None

鉴于 React 不会为 null 值使用默认道具,处理 GraphQL 数据被传递到 React 组件的情况的最佳方法是什么。

例如,我有一个 TagList 组件,我将 GraphQL 查询的结果传递到该组件中。虽然我有以下几点:

TagList.defaultProps = {
  tags: [],
}

如果查询没有返回标签,tags 的值将不是undefined,而是null,因此不应用默认值,组件尝试使用null 作为值进行渲染的标签。

显然我可以在render方法的顶部添加一个检查,并将值设置为[],但感觉必须有更好的解决方案。

【问题讨论】:

  • 尝试使用三元运算符。我只是一个初学者,所以我不确定我是否正确

标签: javascript reactjs graphql default-value react-proptypes


【解决方案1】:

GraphQL 规范不包含未定义值的概念——值只是空值或非空值。事实上,在概述解析字段值的步骤时,它指定 undefined 应该被强制为空值:

如果结果为null(或其他类似于null的内部值,如undefined或NaN),则返回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 响应并根据需要转换 null 或 undefined。 YMMV 与其他 GraphQL 中间件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2019-04-29
    • 2022-06-22
    • 2017-03-17
    • 2017-03-19
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多