javascript - ReactJS 渲染问题获取 API
问题描述
我正在尝试使用 Geolocation 获取 WeatherApp API。我的问题是渲染:它不允许我在获取之前渲染页面(但是在我设法获取之后,代码似乎可以工作)。
返回错误信息:
Type Error : Cannot Read Property 'temp' of undefined
import React, { useState } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
// this line is returning the error
console.log(weather.main.temp)
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
解决方案
获取天气和设置天气状态是异步的,您是weather.main.temp
在请求完成之前进行控制台日志记录。获取数据是 reactjs 的副作用。所以建议你通过使用useEffect
钩子来获取天气信息并在那里设置天气状态。
import React, { useState, useEffect } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
useEffect(() => {
fetchingWeather();
}, [weather])
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
那应该行得通。
推荐阅读
- sql - 如何在存储过程中使用 SQLCMD 变量
- mongodb - 我可以做些什么来使用firebase进行完整的测试搜索或将mongodb全文搜索与firebase连接的最佳方式
- iis - IIS 重写 Content-Disposition 附件文件名
- windows - 我一直在尝试更新我的 SSM 代理。我正在运行命令 AWS updatessmagent
- powerbi - 如何为每周时间段编写 DAX,例如(本周和上周,本周和上个月同一周,本周和去年同一周)
- c++ - OpenCV中积分图像的计算如何如此高效?
- java - 使用 JSONObject 解析 JSON 时出现 IllegalAccessException
- python - 我应该怎么处理这个错误?/ 不支持的操作数类型:“str”和“str”
- javascript - Vue JSON 读写
- python - 为什么要多次插入元素?