【发布时间】:2020-08-17 23:41:34
【问题描述】:
我尝试在我的 useEffect 挂钩中调用两个函数
import React, { useState, useEffect } from "react";
export const LocalWeather = () => {
const APP_KEY = "XXX";
const [userPlace, setUserPlace] = useState([]);
const [localWeather, setLocalWeather] = useState([]);
async function getUserData() {
await fetch("http://ip-api.com/json")
.then((res) => res.json())
.then((data) => {
setUserPlace({
country: data.country,
city: data.city,
});
console.log(data);
})
.catch((err) => console.log(err));
}
async function getLocalWeather() {
await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${userPlace.city}&appid=${APP_KEY}`
)
.then((res) => res.json())
.then((data) => {
setLocalWeather({
temperature: Math.round(data.main.temp - 273.15),
});
})
.catch((err) => console.log(err));
}
useEffect(() => {
getUserData();
getLocalWeather();
});
return (
<div>
<h3>
Your current place is: {userPlace.country}, {userPlace.city}
</h3>
{localWeather.temperature ? (
<h4>Temperature in your city is: {localWeather.temperature} ℃</h4>
) : null}
</div>
);
};
当我尝试将 [] 添加到我的 useEffect 时,eslint 会自动将其更改为:
useEffect(() => {
getUserData();
getLocalWeather();
}, [getLocalWeather]);
我应该怎么做才能只在第一次渲染时调用我的两个函数?
感谢您的帮助!
【问题讨论】:
标签: reactjs react-hooks use-effect