首页 > 解决方案 > GraphQL 查询中带有变量的动态搜索栏

问题描述

我有以下查询在后端运行良好:

{
  fuzzyArticleByTitle(searchString:"tiktok"){
    title
  }
}

结果是几篇文章标题与“tiktok”字符串匹配。

我想用 React 使用 searchString 的变量在前端编写一个动态搜索栏。

我试过这个:

import React, { Component} from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'

const SearchQuery = gql`
query {
    fuzzyArticleByTitle($searchString: String){
        title
  }
}
`;

export default class Search extends Component {

constructor(props) {
    super(props)
    this.state = {
        search: ''
    }
}

updateSearch = (e) => {
    this.setState({
        search: e.target.value
    })
}

submitSearch = (e) => {
    e.preventDefault()
    console.log(this.state)
}

render() {

    const { search } = this.state;

    return (
        <form onSubmit={ this.submitSearch }>
            <input
                type='text'
                onChange={ this.updateSearch }
                value={ search }
                placeholder='Search'
            />
            <Query query={SearchQuery} skip={!search} variables={{query: search}}>
               {({loading, error, data}) => {
                    if (loading) return null;
                    if (error) throw err;
                   return <h1>{data.search.title}</h1>
                }}
            </Query>
        </form>
    )
}
}

它不起作用。我哪里错了?

也许有更好的方法来做到这一点

标签: reactjsgraphqlgrandstack

解决方案


您必须在查询标头中声明变量,例如

query SearchArticles($searchString: String) {
    fuzzyArticleByTitle(searchString: $searchString){
        title
  }
}

然后$在 Apollo 中使用这个特定的变量名(你可以在声明中选择任何名称):

<Query query={SearchQuery} skip={!search} variables={{searchString: search}}>
  {({loading, error, data}) => {
    if (loading) return null;
    if (error) throw err;
     return <h1>{data.search.title}</h1>
  }}
</Query>

推荐阅读