【问题标题】:Retrieving variables for a Relay query fragment from an external store从外部存储中检索 Relay 查询片段的变量
【发布时间】:2017-04-25 10:47:01
【问题描述】:

在编写 GraphQL 查询片段作为 RelayContainer 的一部分时,我一直在努力解决如何在某些情况下设置查询变量。 documentation 中概述的基础知识非常简单。但是考虑到这些查询的静态性质以及 RelayContainer 如何是高阶 React 组件,当查询所需的输入是来自外部源的对象时,我不确定处理这个问题的最佳方法,例如Redux 商店。在组件加载之前,我无法从该存储中检索数据,因此作为一种解决方法,我一直在使用 @include 指令并在组件加载后将就绪变量设置为 true:

class ListData extends React.Component {

  // ... proptypes 

  componentWillMount() {
    const { listDataInfo } = this.context.store.getState(); // Retrieve from Redux store

    this.props.relay.setVariables({
      input: {
        id: listDataInfo.id,
        user: listDataInfo.user
      },
      inputReady: true,
    });

    // The query will now execute and fetch all the data
  }

  render() {
    return (
      {/* view */}
    )
  }
}

export default Relay.createContainer(ListData, {
  initialVariables: {
    input: null,
    inputReady: false,
  },
  fragments: {
    listData: () => Relay.QL`
      fragment on ListDataQuery {
        listData(input: $input) @include(if: $inputReady) {
          city
          state
          zip
          phone
        }
      }
    `,
  },
});

最后,这按预期工作,但我担心这更像是一种 hack,并且我错过了 Relay 应该如何处理查询变量的一些重要内容。有一个更好的方法吗? prepareVariables 看起来很有用,但我仍然无法访问我的数据存储。以下是我的明显选择:

  1. 保持原样
  2. 将其转换为将在组件生命周期方法中执行的突变。我宁愿不这样做,因为它会删除与组件的数据绑定。
  3. 使用自定义RelayNetworkLayer(可以访问我的商店)拦截我的查询并从那里的外部商店设置变量。这也让人感觉像是 hack。

【问题讨论】:

    标签: reactjs relayjs relay react-router-relay react-relay


    【解决方案1】:

    我发现 this gist 完全符合我的要求。它允许您通过带有属性variablesFromState 的装饰器@container 传入redux 状态变量。本质上,它将返回一个标准中继容器(如果未设置 variablesFromState)或一个中继容器,该容器包含在 redux Provider 包装器中,并传入了 redux 存储实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多