从外部存储

时间:2016-12-09 21:27:25

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

当将GraphQL查询片段作为RelayContainer的一部分编写时,我一直在努力解决在某些情况下如何设置查询变量的问题。 documentation中概述的基础知识非常简单。但鉴于这些查询的静态特性以及RelayContainer如何是一个更高阶的React组件,当查询所需的输入是来自外部的对象时,我不确定处理此问题的最佳方法像Redux商店这样的来源。在组件加载之前,我没有办法从该商店检索数据,所以作为一种解决方法,我一直在使用@include指令并在组件加载后将ready变量设置为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
        }
      }
    `,
  },
});

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

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

1 个答案:

答案 0 :(得分:0)

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