reactjs - 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>
)
}
}
它不起作用。我哪里错了?
也许有更好的方法来做到这一点
解决方案
您必须在查询标头中声明变量,例如
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>
推荐阅读
- python - 使用 eval() 对 pd.apply 的 Pandas 性能改进
- node.js - 如何通过流上传和调整大小?
- python - 使用引用另一个 DataFrame 中的索引值的条件参数从多索引 DataFrame 中删除行
- c# - 使用 OAuth2 以编程方式从 ADFS 3.0 获取 access_token
- excel - FormulaArray 命令不适用于少于 255 个字符的公式
- mongodb - 尝试显示来自多个 API 提取的值
- php - date_diff 函数返回的总和值
- asp.net-core - 在 EF Core 中执行 SP
- c++ - 为什么我不能将这个从我的 BST 获取的节点推送到这个堆栈中?
- c++ - 继承类模板的参数化构造函数