【发布时间】:2022-02-10 23:48:41
【问题描述】:
大家好,我在钩子中有这个调用我需要将 lat 和 lng 变量保存在状态中,因为我目前正在这样做它显示以下错误,我希望有人可以帮助我 错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能是由于以下原因之一:
useEffect(() => {
const url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
const http = new XMLHttpRequest();
http.open("POST", url);
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const data = JSON.parse(this.responseText);
const {location: {lat, lng}} = data;
const result = {lat, lng} ;
const [locations, setLocation] = useState({
loaded: true,
coordinates: {
lat: result.lat,
lng: result.lng,
},
aceptacion:1
});
console.log(setLocation);
return result;
}
}
http.send();
}, []);
return location;
};
【问题讨论】:
-
因为您在
useEffect内部使用useState。将其直接移动到您的功能组件定义中
标签: javascript reactjs react-hooks next.js