【问题标题】:Invalid hook call. Hooks can only be called inside of the body of a function component React,JS无效的挂钩调用。 Hooks 只能在 React,JS 函数体内部调用
【发布时间】: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


【解决方案1】:

将 useState 初始化移到 useEffect 挂钩之外。

const [locations, setLocation] = useState({
    loaded: true,
    coordinates: null,
    aceptacion: null,
});

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} ;
       setLocation({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
        return result;
      }
    }
    http.send();
}, []);

return locations;

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2019-11-01
    • 1970-01-01
    • 2020-11-20
    • 2019-12-12
    • 2022-01-25
    • 1970-01-01
    • 2020-06-22
    相关资源
    最近更新 更多