![](/img/trans.png)
[英]How can I stop an infinite render loop if UseEffect() cannot be used in callback in React.js?
[英]Why am I getting an infinite loop in my useEffect (react.js)
基本上我有一个名为 getWeatherForecast 的 function ,它从 api 获取一些天气数据,但是,我得到了一个无限循环,它不断地请求数据无限次。
这是我的 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)
}
这就是我使用 useEffect 的方式
useEffect(() => {
getWeatherForecast()
// console.log(`This is the forecast ${weatherDetails}`)
} , [getWeatherForecast])
知道为什么我会出现无限循环吗?
因为这:
getWeatherForecast
是一个 function ,在每次渲染时都会重新创建。 在 function 内部,您正在调用setWeatherDetails
,它会触发渲染。 因此,在下一次渲染中,创建了 function 的新实例,这与前一个不同,并且再次调用了useEffect
。 将 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,
]);
但是如果我没记错的话,linter 可能会抱怨像props.latitude
这样的依赖关系,并建议在useCallback
之前将其分配给某个变量,然后将其用作依赖项,例如:
let latitude = props.latitude; // then use latitude as dependency
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.