React hook useEffect для извлечения данных не работает для извлечения данных из разных API, может быть проблема oop - PullRequest
0 голосов
/ 21 апреля 2020

Я изучаю перехватчики React и пытаюсь получить информацию о странах из одного API и прогноз погоды для этих стран из другого. Я использую useState для хранения этих данных.

const App = () => {
  const [countries, setCountries] = useState([])
  const [weather, setWeather] = useState([]) 

*//use the first hook to get data on countries*    
  useEffect(() => {
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then(response => {
        setCountries(response.data)
      })
  }, [])

*//want to use the second hook to get weather for all the countries fetched in the first hook*
  useEffect(() => {
    countries.forEach(country => {
      axios
        .get(`http://api.openweathermap.org/data/2.5/weather?q=**${country.capital}**&units=metric&APPID=myAPI`)
        .then(response => {
          const temp = response.data.main.temp
*//concat method does not seem to be working on the next line*
          **setWeather(weather.concat(temp))**
        })
    })
  }, [countries])
*//when I console.log I get temperature for only the last city in the loop and not an array as I expect*
  console.log(weather)

1 Ответ

0 голосов
/ 21 апреля 2020

Когда вы делаете:

setWeather(weather.concat(temp));

Переменная weather не гарантируется для обновления. Передайте предыдущее значение состояния, чтобы сделать объединение:

setWeather((previousWeatherState) => [...previousWeatherState, temp])

Конечный код useEffect будет:

  useEffect(() => {
    countries.forEach(country => {
      axios
        .get(`http://api.openweathermap.org/data/2.5/weather?q=${country.capital}&units=metric&APPID=myAPI`)
        .then(response => {
          const temp = response.data.main.temp
          setWeather((previousWeatherState) => [...previousWeatherState, temp])
        })
    })
  }, [countries])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...