首页 > 解决方案 > Unable to read properties of a property containing the object

问题描述

I'm having an issue trying to access the properties of an object, which has a reference property of another object. In other words, an object contained in other object.

After fetching the data from API calls like this one for example:https://api.apixu.com/v1/current.json?key=2352219608ed457fb3a12903193008&q=Helsinki my code get the response's data and set the hook's value: capitalWeather.

Anyways, the object has two attributes: location and current, which are also object type. Everytime I try to access any value from a reference, like accessing value of capitalWeather.location.region what I get is=

Uncaught TypeError: Cannot read property 'region' of undefined

As expected, It also applies for any of the other attributes: name,country,lat,lon,tz_id,etc....

I don't understand why I'm getting a typeError, considering both are object types.

This is the code snippet where the error takes place:

const Displayer = ({ country }) => {
    const [capitalWeather,setWeather]=useState([]);
    useEffect(() => {
        axios.get(`https://api.apixu.com/v1/current.json?key=2352219608ed457fb3a12903193008&q=${country.capital}`)
            .then(response => {
                console.log('Promise fullfiled, succesfully fetched data');
                setWeather(response.data);
            })
    }, [country.capital]);

    console.log(capitalWeather.location.region);

    return (<div className='displayer'>
        <h2>{country.name}</h2>
        <p>Capital {country.capital}</p>
        <p>Population {country.population}</p>
        <h4>Languages</h4>
        <ul>
            {country.languages.map(lang => <li key={lang.name}>{lang.name}</li>)}
        </ul>
        <img src={country.flag} alt='this is the country flag'></img>
        {/*<Weather weather={capitalWeather}/>*/}
    </div>)
}

标签: javascriptreactjsobjectreact-hooks

解决方案


capitalWeather在这段代码中被初始化为一个数组。

  const [capitalWeather,setWeather]=useState([]);

capitalWeather.location.region肯定会抛出错误,因为它没有属性location


推荐阅读