简体   繁体   English

ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“名称”

[英]ReactJS/Javascript/Graphql/React-apollo: Cannot read property 'name' of undefined

GraphQL Query Defined here GraphQL 查询在此处定义

const countryQuery = gql`
query getQuery($filter: _CountryFilter!) {
    Country(filter: $filter) {
        _id
        name
        capital
        population
        nativeName
    }
  }

`

pages/search.js页面/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 This is were I am getting the error. components/queryResults.js这是我得到的错误。 Is {country.name}, {country.capital} etc. the incorrect way to apply the data here? {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;

在此处输入图像描述

When I type a country and click the search the error is happening on this line: <Card.Title>{country.name}</Card.Title> Why is name, capital, population and nativeName undefined?当我输入国家并单击搜索时,此行发生错误: <Card.Title>{country.name}</Card.Title>为什么名称、首都、人口和 nativeName 未定义? What am I doing wrong?我究竟做错了什么?

I'm looking at this line and would like to note that if data.country is an empty array, it will still be truthy.我正在查看这一行并想指出,如果 data.country 是一个空数组,它仍然是真实的。 Add a check to see if there is a value in the first element of the array before rendering CountryInfo在渲染 CountryInfo 之前添加检查以查看数组的第一个元素中是否有值

{ data?.Country && <CountryInfo country={data?.Country[0]} /> }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM