我正在使用 useEffect 钩子从天气 api 获取数据并正确声明依赖项。我的状态仍未更新,因此我的渲染函数出现错误。我几乎尝试了从摆脱依赖数组到在依赖数组中声明倍数的所有方法。我不知道我的功能有什么问题。API 的 JSON 响应格式如下:
{
location: {
name: "Paris",
region: "Ile-de-France",
},
current: {
last_updated_epoch: 1564279222,
last_updated: "2019-07-28 04:00",
temp_c: 16,
temp_f: 60.8,
is_day: 0,
condition: {
text: "Clear",
icon: "//cdn.apixu.com/weather/64x64/night/113.png",
code: 1000
},
wind_mph: 6.9,
wind_kph: 11.2
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我的代码的样子:
const Weather = ({ capital }) => {
const [weather, setWeather] = useState(null);
useEffect(() => {
console.log("useEffect called");
const getWeather = async () => {
try {
const res = await axios.get(
`http://api.apixu.com/v1/current.json?key=53d601eb03d1412c9c004840192807&q=${capital}`
);
setWeather(res.data); …Run Code Online (Sandbox Code Playgroud)