问题描述
我尝试了许多不同的方式来访问“ main”。我已经尝试过info.main,info [“ main”],info [“-main”],但我不知道如何访问它,并且继续得到未定义的“ temp”。 Info.base可以正常工作。
的样子为什么info.main.temp不起作用,而info.base是为什么? 如果我删除h1 info.main.temp,则只要将其放回应用程序崩溃,页面的呈现就很好。
function Body(props) {
const [location,setLocation] = useState({});
const [info,setInfo] = useState({});
function getGeo() {
navigator.geolocation.getCurrentPosition(function (position) {
setLocation({
lat: position.coords.latitude,long: position.coords.longitude,});
});
}
useEffect(() => {
getGeo();
if (location.lat === undefined || location.long === undefined) {
return;
}
fetch(
`http://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${location.long}&units=metric&appid=key`
)
.then((response) => {
return response.json();
})
.then((result) => {
setInfo(result);
})
.catch((err) => {
console.log(err);
});
},[location.lat,location.long,setInfo]);
return (
<>
<img className="adv" src="image1.png" />
<div className="grid-block-container">
<div className="city-weather">
<div className="info-container">
<h2>{info.base} Weather</h2>
<p>as of 10:31 pm CDT</p>
<h1>{info.main.temp}°</h1>
<h2>Party Cloudy</h2>
<h3>10% chance of rain through 11pm</h3>
</div>
解决方法
您的初始状态是一个空对象({}
)
const [info,setInfo] = useState({});
因此可以访问该对象的base
或main
,并且每个对象最初在第一个渲染上都是undefined
,直到状态更新,但尝试更深入,即{{1 }}将导致错误。
info.main.temp
您可以在更深的属性上使用防护措施
const info = {};
console.log('info',info); // {}
console.log('info.base',info.base); // undefined
console.log('info.main',info.main); // undefined
console.log('info.main.temp',info.main.temp); // error!!
或使用optional chaining检查info.main && info.main.temp
是否存在,然后继续进行main
temp
在任何一种情况下,您可能还希望提供一个备用值,以使info.main?.temp
或undefined
等不会泄漏到用户界面
null
或
(info.main && info.main.temp) || "Loading..."
或
(info.main && info.main.temp) || ""
等...
info.main?.temp || ""