0

我是 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 is not a function。我很困扰。我花了一整天的时间在这上面。如果有人可以提供帮助,非常感谢。

4

1 回答 1

0

useEffect并且useCallback将在依赖项更改时运行。

因此,如果您的依赖项是要在钩子内更改的依赖项,它将触发一个循环。

你不需要useCallback在你的情况下。

只需在里面触发 axios API 方法useEffect,然后设置weatherData无任何依赖的状态即可。

于 2020-11-06T06:56:41.757 回答