问题描述
在此处定义的GraphQL查询
const countryQuery = gql`
query getQuery($filter: _CountryFilter!) {
Country(filter: $filter) {
_id
name
capital
population
nativeName
}
}
`
pages / search.js
export default function Search() {
const [filter,setFilter] = useState({ name: 'Chile' })
const { data,loading,error } = useQuery(countryQuery,{
variables: { filter },})
if (loading){
return <Loader />;
}
if (error) return <p>Error</p>;
return (
<div className="body">
<h1>
Get information
<br /> about Countries!
</h1>
<div className="wrapper">
<input
className="search"
type="text"
id="search"
placeholder='Enter a Country'
/>
<button
className="submit"
type="submit"
value=" "
onClick={e => setFilter({ name: e.target.value })}
onBlur={e => setFilter({ name: e.target.value })}
> Search
</button>
<div>
{ data?.Country && <CountryInfo country={data?.Country[0]} /> }
</div>
</div>
</div>
);
}
components / queryResults.js 这是我遇到的错误。 {country.name},{country.capital}等是在此处应用数据的错误方法吗?
import React from 'react'
import { Card,ListGroup,ListGroupItem } from 'react-bootstrap'
const CountryInfo = ({country}) => (
<div>
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>{country.name}</Card.Title>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>Capital: {country.capital} </ListGroupItem> {' '}
<ListGroupItem>Population: {country.population}</ListGroupItem>
<ListGroupItem>Native Name: {country.nativeName}</ListGroupItem>
</ListGroup>
</Card>
</div>
)
export default CountryInfo;
当我键入国家/地区并单击搜索时,此行上发生错误:<Card.Title>{country.name}</Card.Title>
为什么未定义名称,大写字母,人口和nativeName?我在做什么错了?
解决方法
我正在看这行,并想指出的是,如果data.country是一个空数组,那么它仍然是真实的。添加检查以在呈现CountryInfo之前在数组的第一个元素中查看是否有值
{ data?.Country && <CountryInfo country={data?.Country[0]} /> }