【发布时间】:2020-09-12 03:48:44
【问题描述】:
我尝试了许多不同的方法来访问“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>
【问题讨论】:
-
您能否在代码中显示您进行 API 调用以获取信息的位置?你有什么错误吗?
-
显示您调用 setInfo 的位置
-
api 完全没有错误,正如您在第一张图片中看到的那样,它的设置在我的组件中状态很好,只是由于某种原因它不允许我访问 info.main。就像它只让我访问橙色的键,其他一切都是未定义的。
-
更新了它,但如果 info.base 工作,这怎么可能是原因?
标签: arrays json reactjs object