10

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

所以,工作流程是

  • 用户导航到search form

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

  • 用户填写字段值,然后按操作/搜索按钮。

中继查询被发送到服务器

  • 从服务器接收结果。

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

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

4

2 回答 2

13

如果我理解正确,您不希望在用户输入一些搜索文本之前不为组件发送任何查询,此时应该发送查询。这可以通过@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条件变为真,查询将被发送到服务器。

于 2015-12-21T22:58:53.923 回答
2

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

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,中继将查询新数据。

于 2015-12-18T01:54:25.393 回答