TypeError: Cannot read properties of undefined (reading 'country')
TypeError: Cannot read properties of undefined (reading 'country')
我正在尝试从 API 中获取数据并在我的应用中使用该数据。但问题是,当我尝试从 JSON 中获取某个对象或数据时,我刚刚从 API 中获取,我得到一个 TypeError: Cannot read 属性 'country' 的未定义。
属性 确实存在。
顺便说一下,我正在使用 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);
});
}
};
}
问题是因为您的天气检查:typeof weather != 'undefined'
而您的天气初始值是 {}
。为了解决这个问题,不要为天气设置初始值。像这样:
const [weather, setWeather] = useState();
因此,在第一个渲染中天气值将是 undefined
,在下一个渲染中它将包含您的 api 响应。
如果您确定 属性 确实存在,那么它一定是初始渲染。你用 {}
初始化 useStaet
但要防止 undefined
。
所以将 useState({})
更改为 useState()
.
const [weather, setWeather] = useState();
读country
.
时也可以加空检查
{weather.name}, {weather.sys?.country}
我正在尝试从 API 中获取数据并在我的应用中使用该数据。但问题是,当我尝试从 JSON 中获取某个对象或数据时,我刚刚从 API 中获取,我得到一个 TypeError: Cannot read 属性 'country' 的未定义。 属性 确实存在。 顺便说一下,我正在使用 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);
});
}
};
}
问题是因为您的天气检查:typeof weather != 'undefined'
而您的天气初始值是 {}
。为了解决这个问题,不要为天气设置初始值。像这样:
const [weather, setWeather] = useState();
因此,在第一个渲染中天气值将是 undefined
,在下一个渲染中它将包含您的 api 响应。
如果您确定 属性 确实存在,那么它一定是初始渲染。你用 {}
初始化 useStaet
但要防止 undefined
。
所以将 useState({})
更改为 useState()
.
const [weather, setWeather] = useState();
读country
.
{weather.name}, {weather.sys?.country}