[英]Why am I getting an infinite loop in my useEffect (react.js)
Basically I have a function called getWeatherForecast which gets some weather data from an api however, I am getting an infinite loop and it keeps requesting for the data an infinite number of times.基本上我有一个名为 getWeatherForecast 的 function ,它从 api 获取一些天气数据,但是,我得到了一个无限循环,它不断地请求数据无限次。
Here is my function这是我的 function
const getWeatherForecast = async () => {
const weatherForecast = await axios.get(`${API_ENDPOINT}lat=${props.latitude}&lon=${props.longitude}&exclude=hourly,daily&appid=${API_KEY}`)
console.log(weatherForecast)
setWeatherDetails(weatherForecast)
}
This is how I used the useEffect这就是我使用 useEffect 的方式
useEffect(() => {
getWeatherForecast()
// console.log(`This is the forecast ${weatherDetails}`)
} , [getWeatherForecast])
Any idea why I am getting an infinite loop?知道为什么我会出现无限循环吗?
Because this:因为这:
getWeatherForecast
is a function which gets recreated on each render.是一个 function ,在每次渲染时都会重新创建。 Inside that function you are calling a
setWeatherDetails
, which triggers a render.在 function 内部,您正在调用
setWeatherDetails
,它会触发渲染。 Hence on the next render a new instance of that function is created, which is different from the previous one, and useEffect
is called again.因此,在下一次渲染中,创建了 function 的新实例,这与前一个不同,并且再次调用了
useEffect
。 Wrap that function in useCallback .将 function 包装在useCallback中。
let getWeatherForecast = React.useCallback(async () => {
const weatherForecast = await axios.get(
`${API_ENDPOINT}lat=${props.latitude}&lon=${props.longitude}&exclude=hourly,daily&appid=${API_KEY}`
);
console.log(weatherForecast);
setWeatherDetails(weatherForecast);
}, [
/*
* put the dependencies here
* if API_ENDPOINT and API_KEY are defined outside the component no need to put them as dependency
*/
props.latitude,
props.longitude,
]);
But If I remember correctly linter may complain about dependency like props.latitude
and suggest to assign it to some variable before the useCallback
, and then use that as a dependency like:但是如果我没记错的话,linter 可能会抱怨像
props.latitude
这样的依赖关系,并建议在useCallback
之前将其分配给某个变量,然后将其用作依赖项,例如:
let latitude = props.latitude; // then use latitude as dependency
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.