【发布时间】:2022-01-11 11:09:38
【问题描述】:
我正在尝试从 API 获取数据并在我的应用中使用该数据。但问题是,当我尝试从我刚刚从 API 获得的 JSON 中获取某个对象或数据时,我得到一个 TypeError: Cannot read property 'country' of undefined。 该属性确实存在。 顺便说一句,我正在使用 React.js。 我非常感谢您的帮助和指导。 代码如下:
App.js
{typeof weather != 'undefined' ? (
<div>
<div className="location-box">
<div className="location">
{weather.name},{weather.sys.country}
</div>
<div className="date"> {dateBuilder(new Date())} </div>
</div>
<div className="weather-box">
<div className="weather-temperature">15*C</div>
<div className="weather">Sunny </div>
</div>
</div>
) : ("NULL")}
我们要从中获取数据的 API。
function App() {
const [query, setQuery] = useState("");
const [weather, setWeather] = useState({});
const Search = (evt) => {
if (evt.key === "Entre") {
debugger;
fetch(`${api.base}weather?q=${query}&units=metric&APPID${api.key}`)
.then((res) => res.json())
.then((result) => {
setWeather(result);
setQuery("");
console.log(result);
});
}
};
}
【问题讨论】:
-
该属性不存在,因为最初呈现组件时您没有数据。你有一个空对象。它可能在数据中,但您需要在加载数据后并更新状态。
-
您能否
console.logweather变量并查看weather.sys是否真的存在? -
好的,我会在控制台查看天气
-
把这个:
{weather.name},{weather.sys?.country}
标签: javascript reactjs react-redux react-hooks