javascript - 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>)
}
解决方案
capitalWeather
在这段代码中被初始化为一个数组。
const [capitalWeather,setWeather]=useState([]);
capitalWeather.location.region
肯定会抛出错误,因为它没有属性location
。
推荐阅读
- python - Python PySerial 超时
- c# - dotnetcore http 线程异步等待难题
- dax - 如何根据列中的值名称获取较早的值
- javascript - 定义没有 function 关键字或箭头函数语法的方法
- java - RecyclerView 的波纹效果不会在简单的点击时显示
- android - ARCore Pose 和 Aruco 估计PoseSingleMarkers
- css - 有没有办法验证某些 CSS 文件是否是从某个 LESS 文件编译的?
- java - 如何配置 OpenTracing Tracer 以在 Java 中将数据推送到 Prometheus/Grafana
- r - 如何插入另一列的值?
- angular - Bing Map V8 读取 GeoJson 查找质心并添加图钉