【问题标题】:Is it possible to pass a city obtained from the API to the following function?是否可以将从 API 获得的城市传递给以下函数?
【发布时间】:2021-12-04 07:41:47
【问题描述】:

我有以下功能通过使用纬度和经度的 API 检索城市:

export const GeoLocation = async () => {
    const geolocation = useGeolocation();
    const latitude = geolocation.latitude;
    const longitude = geolocation.longitude

  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
  const res = await axios.get(url);
  let setCityLocation = {
   city: res.data.name,
  
  }
 console.log(setCityLocation);
 
}

如何将恢复的城市名称传递给以下语句:

const [city, setCity] = useState('Turi');

我必须输入地理定位的位置,而不是显示“Turi”的城市。

我拥有所有这些调用城市常量的特征:

 const handleCityWeather = () => {
    getCityWeather(city)
    .then((setData) => {
      setWeather(setData);
      setIsHeartSelected(false);
      setLoading(false);

    })
    .catch((error) => {
      setError(true);
    })
  }

  const handleForeCast = (city) => {
    getCityForecast(city)
    .then((forecast) => {
      setForecast(forecast);
      setError(false);
    })
    .catch((error) => {
      setError(true);
    })
  }
  useEffect(() => {
    if (!city) {
      return;
    }
    handleCityWeather(city)
  }, [city, isError])

  useEffect(() => {
    if (!city) {
      return;
    }
    handleForeCast(city)
  }, [city, isError])

  const debouncedSearchTerm = useDebounce((value) => setCity(value), delay);

  const onInputChange = (value) => debouncedSearchTerm(value);

  const getSearchWeather = (event) => {
    event.preventDefault();
    getCityWeather(city);
    getCityForecast(city); 
  }

我应该改变什么值?

【问题讨论】:

    标签: reactjs geolocation weather


    【解决方案1】:

    如果你有以下状态:

    const [city, setCity] = useState('Turi');

    要更新city 的值,您只需调用setCity,如下所示:

    setCity(setCityLocation)

    您的代码可能如下所示:

    const [city, setCity] = useState('Turi');
    
    export const GeoLocation = async () => {
        const geolocation = useGeolocation();
        const latitude = geolocation.latitude;
        const longitude = geolocation.longitude
    
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const res = await axios.get(url);
        let setCityLocation = {
            city: res.data.name,
        }
        
        // This function updates the value of city
        setCity(setCityLocation);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 2012-05-08
      相关资源
      最近更新 更多