【问题标题】:Fetching weather data from Foreca weather API in react在反应中从 Foreca 天气 API 获取天气数据
【发布时间】:2022-12-18 07:33:09
【问题描述】:

我正在尝试从 Foreca Weather api (https://rapidapi.com/foreca-ltd-foreca-ltd-default/api/foreca-weather/) 获取天气数据。 要获取当前天气,需要 location 参数,它是一串数字,因城市而异。这个位置参数可以从他们的位置搜索端点获取。

我有一个函数 searchCity,它获取位置 ID,然后将其传递给 weatherUrl 以获取当前天气。 第一次搜索城市时,我确实得到了位置数组,但不是当前天气,axios 会抛出 400 错误请求错误。 我第二次搜索时,它给了我两个,但当前的天气响应来自上次 api 调用。

Here's the code.
import React from 'react'
import { useState } from 'react';
import axios from 'axios';
const Home = () => {
  // const [weather, setWeather] = useState({});
  const [city, setCity] = useState('');
  const [location, setLocation] = useState([""]);
  const [weather, setWeather] = useState({});


  const url = `https://foreca-weather.p.rapidapi.com/location/search/${city}`
  let weatherUrl;
  const options = {
    headers: {
      'X-RapidAPI-Key': 'apiKeyHere',
      'X-RapidAPI-Host': 'foreca-weather.p.rapidapi.com'
    }
  };
  const weatherOptions = {
    params: { alt: '0', tempunit: 'C', windunit: 'MS', tz: 'Europe/London', lang: 'en' },
    headers: {
      'X-RapidAPI-Key': 'apiKeyHere',
      'X-RapidAPI-Host': 'foreca-weather.p.rapidapi.com'
    }
  };

  const searchCity = async (e) => {
    try {
      if (e.key === 'Enter') {
        await axios.get(url, options).then((response) => {
          setLocation(response.data.locations);
          console.log(response.data);
          weatherUrl = `https://foreca-weather.p.rapidapi.com/current/${location[0]?.id}`;
        })
        setCity('')

// To show the current weather of the city searched

        currentWeather(); 


      }
    } catch (err) {
      console.error(err);
    }
  }

  const currentWeather = async () => {
    try {
      await axios.get(weatherUrl, weatherOptions).then((response) => {
        setWeather(response.data);
        console.log(response.data);
      })
    } catch (err) {
      console.error(err);
    }

  }
  return (
    <> <div>
        <div className="search">
          <input
            value={city}
            onChange={e => setCity(e.target.value)}
            onKeyPress={searchCity}
            type="text" />
        </div>

        <div className="weather">
          <h1>City:{location[0]?.name}</h1>
          <h1>Country:{location[0]?.country}</h1>
          <h1>id:{location[0]?.id}</h1>
          <h1>weather:{weather.current?.temperature}</h1>
        </div>
      </div>
    </>

  )
}

export default Home;


What am I doing wrong or are there better ways to achieve this?

【问题讨论】:

    标签: javascript reactjs rest axios fetch-api


    【解决方案1】:

    从位置请求的响应设置新状态时,您尝试立即地访问状态。这是不可能的,因为状态不会立即更新。这解释了从前一个城市获取结果的问题。

    await axios.get(url, options).then((response) => {
      setLocation(response.data.locations);
      console.log(response.data);
      // weatherUrl = `https://foreca-weather.p.rapidapi.com/current/${location[0]?.id}`;
    });
    

    为避免这种情况,您可以像对url 那样做

    const url = `https://foreca-weather.p.rapidapi.com/location/search/${city}`;
    
    const weatherUrl = `https://foreca-weather.p.rapidapi.com/current/${location[0]?.id}`;
    

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 1970-01-01
      • 2020-11-25
      • 2021-08-07
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多