首页 > 解决方案 > 如何将带有“throw”的 if 条件放入 fetch...then API

问题描述

我需要在 fetch - .then 函数中放置一个带有 throw 的 if 条件,以检查响应数据是否正确,但我不知道该怎么做。

getWeather = (latitude, longitude) => {
    const API_KEY = "";
    const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

    fetch(api)
      .then(response => response.json())
      .then(data => { 
        this.setState({ 
          locationName: data.name,
          temperature: data.main.temp,
          weatherDescription: data.weather[0].description,
          isLoading: false, 
        })

      })
  };

标签: reactjstry-catch

解决方案


像这样:

fetch(api)
      .then(response => response.json())
      .then(data => {     
               if(**YOUR_CONDITION_HERE**){

                  this.setState({ 
                   locationName: data.name,
                   temperature: data.main.temp,
                   weatherDescription: data.weather[0].description,
                   isLoading: false, 

               } else {

                  throw new Error("data invalid");

       }).catch(err => console.log(err));

推荐阅读