ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“name”
2020-08-13
736
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>
为什么 name、capital、population 和 nativeName 未定义?我做错了什么?
1个回答
我正在查看此行,并想指出,如果 data.country 是一个空数组,它仍将为真。在呈现 CountryInfo 之前添加检查以查看数组的第一个元素中是否有值
{ data?.Country && <CountryInfo country={data?.Country[0]} /> }
MarkCBall
2020-08-13