使用中继的搜索功能

search functionality using relay

如何使用中继实现搜索功能?

所以,工作流程是

初始化视图时不应有任何查询(如在中继容器中)。

向服务器发送中继查询

页面显示它并中继协调 filtered 结果与本地缓存。

我没有看到临时查询的示例,只是中继容器的一部分(它在组件初始化之前解析)。那么,如何建模呢。它应该像一个突变吗?

这是我在我的项目中实现简单搜索的方式:

export default Relay.createContainer(Search, {
  initialVariables: {
    count: 3,
    title: null,
    category: null,
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        items(first: $count, title: $title, category: $category) {
          edges {
            node {
              ...
            }
          }
        }
      }
    `,
  },
});

您的搜索表单只需使用 this.props.relay.setVariables 更新 initialVariables,中继将查询新数据。

如果我理解正确的话,您不希望在用户输入一些搜索文本之前不发送任何对该组件的查询,此时应发送查询。这可以通过@Xuorig 发布的示例来完成,并添加一个:使用 GraphQL 的 @include 指令跳过片段,直到设置变量。这是扩展示例:

export default Relay.createContainer(Search, {
  initialVariables: {
    count: 3,
    query: null,
    hasQuery: false, // `@include(if: ...)` takes a boolean
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        # add `@include` to skip the fragment unless $query/$hasQuery are set
        items(first: $count, query: $query) @include(if: $hasQuery) {
          edges {
            node {
              ...
            }
          }
        }
      }
    `,
  },
});

最初将跳过此查询,因为包含条件为假。然后,组件可以在文本输入更改时调用 setVariables({query: someQueryText, hasQuery: true}),此时 @include 条件将变为真,查询将发送到服务器。