如何解决ReactJS挂钩 TypeError:Object...不是函数
我是reactJS的新手,我正在尝试使用React Hooks开发天气应用程序。 useEffect挂钩无限运行,即使依赖关系也与以前相同。因此,我决定使用useCallBack挂钩,但是它显示了一个错误。
代码如下:
import React,{useState,useEffect,useCallBack} from 'react';
import axios from 'axios';
const WeatherApp = () =>{
const [weatherData,setWeatherData] = useState({
latitude:1,longitude:0,city:'',country:'',description:'',temperature:'',apiKey:"96f70a610a2b066259b75fc8d23eab98",icon:''
});
const getWeatherByCoords = useCallBack(()=>{
let api=`http://api.openweathermap.org/data/2.5/weather?lat=${weatherData.latitude}&lon=${weatherData.longitude}&appid=${weatherData.apiKey}`;
axios.get(api)
.then(res=>{
const data = res.data;
setWeatherData(pre=>({...pre,country:data.sys.country,city:data.name,temperature:data.main.temp,description:data.weather[0].description
}));
console.log(weatherData);
})
.catch(error=>errorHandler(error));
},[weatherData]);
const errorHandler = error=>{
console.log(error);
}
useEffect(()=>{
// const interval = setInterval(()=>{
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(position=>{
setWeatherData({...weatherData,latitude:position.coords.latitude,longitude:position.coords.longitude});
getWeatherByCoords();
},error=>errorHandler(error),{timeout:10000});
}
// },1000);
// return(()=> clearInterval(interval));
},[getWeatherByCoords]);
// fetch(`api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`)
return(
<div>
<div>
<h1>City</h1>
<h2>Date</h2>
<h3>Description</h3>
</div>
<div>
<img alt='This is an img'></img>
<h2>Temperature</h2>
<p> <span>°C</span>|<span>°F</span></p>
</div>
</div>
)
};
export default WeatherApp;
错误:
如果我使用useMemo,则错误将变为:getWeatherByCoords不是函数。我很困扰。我花了整整一整天的时间。非常感谢任何人的帮助。
解决方法
useEffect
和useCallback
将在依赖项更改时运行。
因此,如果您的依赖关系是将在挂钩内更改的依赖关系,则会触发循环。
您不需要useCallback
。
只需在useEffect
内触发axios API方法,然后在没有任何依赖性的情况下设置weatherData
的状态即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。