繁体   English   中英

如何使用 IF 语句避免用户输入错误的城市名称时 Weather API 获取结果崩溃?

[英]How to use the IF statement to avoid the Weather API fetch result crashing once the user types wrong the city name?

总结问题

- 关于目标的详细信息

一个天气应用程序,它在屏幕上呈现从 OpenWeather API 获取的数据。

- 实际和预期结果

无论用户是否正确键入城市名称或在空白字段中按回车,屏幕上都不会呈现结果。 我想帮助解决它。

迄今为止的尝试(更新 1.1)

我在 *App.js* 文件中的 *Search* 组件下方放置了一个条件运算符:

{typeof dataSearch === "undefined" ? (<></>) : ()}
{typeof dataSearch === "undefined" ? (
  <></>
) : (
  <>
    <CurrentWeather resultData={weatherData} />
    <ForecastWeather resultData={forecastData} />
  </>
)}

我不希望它会让屏幕空白。

嗯,谢谢你阅读我的帖子。

完整代码

- App.js(更新 1.1)
import React, { useState } from "react";
import { Api } from "./Api";
import { Container } from "react-bootstrap";
import {
  Search,
  CurrentWeather,
  ForecastWeather,
  Footer,
} from "./components/index";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  const [weatherData, setWeatherData] = useState(null);
  const [forecastData, setForecastData] = useState(null);

  const handleSearchLocation = (dataSearch) => {

    const weatherDataFetch = fetch(
      `${Api.url}/weather?q=${dataSearch}&units=metric&appid=${Api.key}`
    );
    const forecastDataFetch = fetch(
      `${Api.url}/forecast?q=${dataSearch}&units=metric&appid=${Api.key}`
    );

    Promise.all([weatherDataFetch, forecastDataFetch]).then(
      async (response) => {
        const weatherResponse = await response[0].json();
        const forecastResponse = await response[1].json();

        setWeatherData(weatherResponse);
        setForecastData(forecastResponse);
      }
    );
  };

  return (      
    <div className="App">
      <div className="contentApp">
        <Container>
          <Search
            searchResultData={handleSearchLocation}
            textPlaceholder="Search for a place..."
          />
          {typeof dataSearch === "undefined" ? (<></>) : (
            <>
          <CurrentWeather resultData={weatherData} />
          <ForecastWeather resultData={forecastData} />
          </>
          )}
          <Footer />
        </Container>
      </div>     
    </div>
  );
}

export default App;

Yippee-ki-yay

总结问题

我面临的主要问题是处理 API 逻辑以在屏幕上显示搜索结果,在此之前,一旦用户输入错误的城市名称或在空白输入字段中按下输入,程序就会崩溃。

但是,我已经开始寻找为什么会发生这种情况,并且在观察其他代码之后,我发现应该使用 IF 语句来解决这个问题。

问题解决

经过多次尝试,解决方案是删除Promise.all()并将它们(天气和预报)分离为具有自己的 IF 语句的等待代码块:

// App.js
    await weatherDataFetch
      .then((res) => {
        if (!res.ok) {
          throw new Error("City name: typed wrong or blank input.");
        }
        return res.json();
      })
      .then((res) => {
        setWeatherData(res);
      })
      .catch((err) => {
        console.log(err);
      });

    await forecastDataFetch
      .then((res) => {
        if (!res.ok) {
          throw new Error(
            "Weather forecast not found. Waiting for the correct city name."
          );
        }
        return res.json();
      })
      .then((res) => {
        setForecastData(res);
      })
      .catch((err) => {
        console.log(err);
      });

异步已移至句柄搜索位置function的顶部:

// App.js
const handleSearchLocation = async (dataSearch) => {

最后,删除清理和避免冲突和崩溃的旧尝试:

// Old
// App.js
  return (      
    <div className="App">
      <div className="contentApp">
        <Container>
          <Search
            searchResultData={handleSearchLocation}
            textPlaceholder="Search for a place..."
          />
          {typeof dataSearch === "undefined" ? (<></>) : (
            <>
          <CurrentWeather resultData={weatherData} />
          <ForecastWeather resultData={forecastData} />
          </>
          )}
          <Footer />
        </Container>
      </div>     
    </div>
  );
// New
// App.js
  return (
    <div className="App">
      <div className="contentApp">
        <Container>
          <Search
            searchResultData={handleSearchLocation}
            textPlaceholder="Search for a place..."
          />
          {weatherData && <CurrentWeather resultData={weatherData} />}
          {forecastData && <ForecastWeather resultData={forecastData} />}
          <Footer />
        </Container>
      </div>
    </div>
  );
笔记

像我这样的其他初学者会观察其他代码,尤其是相同程序的代码变体,因为有很多方法可以做同样的事情。

Yippee-ki-yay

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM