您需要将其拆分为至少两个组件。一个保存用户搜索内容的状态,然后另一个通过获取props实际进行查询。此外,如果表单是在未输入任何内容的情况下提交的,您可以让 apollo 高阶组件跳过查询。
import React, {Component} from 'react'
import {graphql} from 'react-apollo'
import gql from 'graphql-tag'
class Results extends Component {
render() {
// apollo provides results under the data prop
const {data} = this.props;
return <h1>{data.search.namej}</h1>
}
}
const ResultsWithQuery = graphql(gql`
query FindTeam($query: String!) {
search(query: $query, type: TEAM) {
name
}
}
`, {skip: (ownProps) => !ownProps.query})(Results);
export 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 (
<div>
<form onSubmit={this.submitSearch}>
<input
type='text'
onChange={this.updateSearch}
value={search}
placeholder='Search'
/>
<ResultsWithQuery query={search} />
</form>
</div>
)
}
}
* 更新 *
现在 react-apollo@2.1 已经发布,有一种使用渲染props的替代方法。
https://www.apollographql.com/docs/react/essentials/get-started.html#request
在这种情况下,这简化了您需要的组件数量。
import React, { Component} from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'
const SearchQuery = gql`
query FindTeam($query: String!) {
search(query: $query, type: TEAM) {
name
}
}
`;
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.namej}</h1>
}}
</Query>
</form>
)
}
}