Weather API React [关闭]

问题描述 投票:0回答:0

虽然我的代码输出正确,但我更关心结构以及它是否符合 API“应用程序”的标准。我在下面提供我的代码,它在我的 App.js 文件中,对它有什么建议,因为我想稍后将它放入我的投资组合中?

import { useState } from "react";

function App() {
  const api = {
    key: "c6440629646261c9d5423619112f0341",
    base: "http://api.openweathermap.org/data/2.5",
  };

  const [search, setSearch] = useState("");
  const [weather, setWeather] = useState({});
  const [error, setError] = useState(null);

  const searchPressed = () => {
    fetch(`${api.base}/weather?q=${search}&units=metric&APPID=${api.key}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error("Network response was not ok");
        }
        return res.json();
      })
      .then((result) => {
        setWeather(result);
        setError(null);
      })
      .catch((error) => {
        console.log(error);
        setError("Something went wrong. Please try again.");
      });
  };

  return (
    <div className="container mx-auto mt-8">
      <h1 className="mb-4 text-3xl font-bold">Weather App</h1>
      {/* Search Box */}
      <div className="flex mb-4">
        <input
          type="text"
          placeholder="Enter a city"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full p-2 mr-2 border-2 border-gray-200 rounded-lg focus:outline-none focus:border-blue-500"
        />
        <button
          onClick={searchPressed}
          className="px-4 py-2 font-bold text-white bg-blue-500 rounded-lg hover:bg-blue-700"
        >
          Search
        </button>
      </div>
      {/* Ternary operation */}
      {typeof weather.main != "undefined" ? (
        <div className="text-center">
          <p className="text-lg">
            {weather.name}, {weather.sys.country}
          </p>
          <p className="text-6xl font-bold">{weather.main.temp} C°</p>
          <p className="text-lg">Feels like: {weather.main.feels_like} C°</p>
          <p className="text-lg">{weather.weather[0].main}</p>
        </div>
      ) : error ? (
        <p className="text-center text-red-500">{error}</p>
      ) : null}
    </div>
  );
}

export default App;

我想做的一件事是通过按键盘上的“返回”键使搜索按钮起作用。我该如何开始?

javascript reactjs react-hooks weather-api
© www.soinside.com 2019 - 2024. All rights reserved.