【问题标题】:Why i am getting too many response from the API call为什么我从 API 调用中得到太多响应
【发布时间】:2021-03-18 02:47:11
【问题描述】:

我无法停止 api 调用。处理这种情况的正确方法应该是什么。

const successCallback = (position) => {
    console.log("in success");
    setCoord({ ...coord, latitude: position.coords.latitude.toFixed(4), longitude: position.coords.longitude.toFixed(4) })
  }
  const failCallback = () => {
    alert("Give Location Permission for currect Location.")
  }
  if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(successCallback, failCallback)
  } else {
    alert("Geolocation is not supported by this browser.")
  }
  const url3 = `http://api.openweathermap.org/data/2.5/weather?lat=${coord.latitude}&lon=${coord.longitude}&appid=MYKEY`
  const fetchWeather = async () => {
    const responce = await Axios.get(url3)
    console.log(responce);
  }
  useEffect(() => {
    fetchWeather()
  }, [coord])

【问题讨论】:

    标签: reactjs api geolocation use-effect


    【解决方案1】:

    添加选项以限制调用successCallback 的频率

    const options = {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 20000
    };
    window.navigator.geolocation.getCurrentPosition(successCallback, failCallback, options)
    

    或者如果你希望它只被调用一次,使用

    const options = {
      timeout: 0
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2021-12-02
      • 2020-03-28
      • 2019-12-16
      • 1970-01-01
      • 2016-11-22
      • 2019-04-12
      相关资源
      最近更新 更多