【问题标题】:ReactJS/Javascript/Graphql/React-apollo: Cannot read property 'name' of undefinedReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“名称”
【发布时间】:2020-12-03 19:01:24
【问题描述】:

此处定义的 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;

当我输入国家并单击搜索时,此行出现错误:&lt;Card.Title&gt;{country.name}&lt;/Card.Title&gt; 为什么名称、首都、人口和 nativeName 未定义?我做错了什么?

【问题讨论】:

    标签: javascript reactjs graphql react-apollo


    【解决方案1】:

    我正在查看这一行并想指出,如果 data.country 是一个空数组,它仍然是真实的。在渲染 CountryInfo 之前添加检查以查看数组的第一个元素中是否有值

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

    【讨论】:

    • { data?.Country &amp;&amp; &lt;CountryInfo country={data?.Country[0] === 0} 这样的东西会起作用吗?我得到了一个空数组和我在网络选项卡中搜索的国家/地区。
    • 尝试{ data?.Country?.[0] &amp;&amp; &lt;CountryInfo country={data?.Country[0]} /&gt; } 这样data?.Country?.[0] 将是虚假的,除非数组的第一个元素中有一个实际的国家/地区。
    猜你喜欢
    • 2019-01-25
    • 2020-07-06
    • 2020-02-01
    • 2021-12-06
    • 2019-05-12
    • 2021-12-28
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多