2 ax ios запросить рендеринг проблемы перед получением данных из запроса - PullRequest
0 голосов
/ 22 марта 2020

Я создаю приложение, похожее на AccuWeather в React. js.

У меня проблема с запросом ax ios .get. Мне нужно получить данные с 2 URL. Второй запрос (прогноз) больше. Из-за этого, когда я хочу получить прогноз погоды для города в определенных частях приложения, DOM визуализируется до того, как я получу данные из запроса Ax ios.

Я пытался использовать asyn c и ждал в своем коде, но безуспешно. Ниже вы можете найти функцию getCityWeather , которая содержит запрос 2 Ax ios. Есть идеи?

getCityWeather = event => {
  axios
    .get(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
        this.state.city +
        "&units=metric&appid=" +
        this.state.appiID
    )
    .then(weather => {
      console.log(weather);
      this.setState({
        currentCityWeather: weather.data.weather,
        currentCityName: weather.data.name,
        currentCityCountry: weather.data.sys.country,
        CityWeatherMain: weather.data.main,
        CityWeatherWind: weather.data.wind,
        CityWeatherClound: weather.data.clouds,
        cityLoaded: true
      });
    })
    .catch(error => {
      console.log(error);
    });

  axios
    .get(
      "https://api.openweathermap.org/data/2.5/forecast?q=" +
        this.state.city +
        "&units=metric&appid=" +
        this.state.appiID
    )
    .then(forecast => {
      console.log(forecast);
      this.setState({
        CityForecastDataList: forecast.data.list,
        cityLoaded: true
      });
    })
    .catch(error => {
      console.log(error);
    });
  event.preventDefault();
};

Ответы [ 2 ]

0 голосов
/ 22 марта 2020

Спасибо за ответ, Кирилл,

Я пытался реализовать ваш код, но получил

ReferenceError: Cannot access 'promises' before initialization
getCityWeather
src/containers/WeatherData/WeatherData.js:39
  36 |   `${baseUrl}/weather?q=${city}&units=metric&appid=${appiID}`,
  37 |   `${baseUrl}/forecast?q=${city}&units=metric&appid=${appiID}`
  38 | ];
> 39 | const promises = urls.map(s => axios.get(s),
     | ^  40 | 
  41 | Promise.all(promises)
  42 |   .then(([weatherResponse, forecastResponse]) => {

Ниже, пожалуйста, найдите мою реализацию для компонента на основе классов, который я использую


getCityWeather = (event) => {
    event.preventDefault();
    const baseUrl = 'https://api.openweathermap.org/data/2.5';

    const { city, appiID } = this.state;
    const urls = [
      `${baseUrl}/weather?q=${city}&units=metric&appid=${appiID}`,
      `${baseUrl}/forecast?q=${city}&units=metric&appid=${appiID}`
    ];
    const promises = urls.map(s => axios.get(s));

    Promise.all(promises)
      .then(([weatherResponse, forecastResponse]) => {
        const {
          date: {
            weather,
            name,
            sys: { country },
            main,
            wind,
            clouds
          },
        } = weatherResponse;
        const {
          data: { list },
        } = forecastResponse;

        this.setState({
          currentCityWeather: weather,
          currentCityName: name,
          currentCityCountry: country,
          CityWeatherMain: main,
          CityWeatherWind: wind,
          CityWeatherClound: clouds,
          CityForecastDataList: list,
          cityLoaded: true,
        });
      })
      .catch(({ message }) => {
        console.error(message);
      })
    )}
0 голосов
/ 22 марта 2020

Попробуйте код ниже.

const baseUrl = 'https://api.openweathermap.org/data/2.5';

const getCityWeather = (event) => {
  event.preventDefault();
  const { city, appiID } = this.state;
  const urls = [
    `${baseUrl}/weather?q=${city}&units=metric&appid=${appiID}`,
    `${baseUrl}/forecast?q=${city}&units=metric&appid=${appiID}`,
  ];
  const promises = urls.map(s => axios.get(s));
  
  Promise.all(promises)
    .then(([weatherResponse, forecastResponse]) => {
      const {
        date: {
          weather,
          name,
          sys: { country },
          main,
          wind,
          clouds,
        },
      } = weatherResponse;
      const {
        data: { list },
      } = forecastResponse;

      this.setState({
        currentCityWeather: weather,
        currentCityName: name,
        currentCityCountry: country,
        CityWeatherMain: main,
        CityWeatherWind: wind,
        CityWeatherClound: clouds,
        CityForecastDataList: list,
        cityLoaded: true,
      });
    })
    .catch(({ message }) => {
      console.error(message);
    });
};
...