我正在尝试创建一个天气应用程序,我目前卡在搜索栏上。我在一个名为 Inputs.tsx 的组件中工作(存储我的搜索栏和按钮以显示不同的温度(F 和 C)
我能够显示天气的当前位置(现在是伦敦)但是一旦我在 div 中按退格键我立即收到以下错误:
编译有问题: × 错误 无法读取未定义的属性(读取“名称”) 类型错误:无法读取未定义的属性(读取“名称”)
我知道该值已设置为当前默认位置,但是在输入另一个城市后如何更改它以及如何使其显示在我的 App 组件中?
Inputs.tsx
import React, { useEffect, useState } from "react";
import { GrLocation } from "react-icons/gr";
import { AiOutlineSearch } from "react-icons/ai";
function Inputs() {
const [weather, setWeather] = useState<any>();
useEffect(() => {
async function load() {
const weatherData = await getWeather();
setWeather(weatherData);
console.log(weatherData);
}
load();
}, []);
if (!weather) {
return <p>loading</p>;
}
const handleSearch = () => {
if (weather !== "") setWeather({ q: weather });
};
return (
<div>
<div id="search-container">
<AiOutlineSearch onClick={handleSearch} />
<input
id="search-bar"
type="text"
placeholder="Search.."
value={weather.location.name}
onChange={(e) => setWeather(e.currentTarget.value)}
></input>
<GrLocation />
<div className="temperature">
<button name="metric" id="fahrenheit-button">
°F
</button>
<p>|</p>
<button name="imperial" id="celcius-button">
°C
</button>
</div>
</div>
</div>
);
}
async function getWeather() {
const response = await fetch(
"https://api.weatherapi.com/v1/current.json?key=462eaa5d277d46b0957222907232503&q=London&aqi=no"
);
return response.json();
}
export default Inputs;
App.tsx
import { useEffect, useState } from "react";
import { ReactComponent as Logo } from "../src/mag-glass.svg";
import "./App.css";
import Inputs from "./components/Inputs";
import TemperatureAndDetails from "./components/TemperatureAndDetails";
import TimeAndLocation from "./components/TimeAndLocation";
function App() {
const [weather, setWeather] = useState<any>();
useEffect(() => {
async function load() {
const weatherData = await getWeather();
setWeather(weatherData);
console.log(weatherData);
}
load();
}, []);
if (!weather) {
return <p>loading</p>;
}
return (
<div className="App">
<header className="App-header"></header>
<Inputs />
<TimeAndLocation />
<h1>Weather in {weather.location.name}</h1>
<h1 id="temp-display">{weather.current.temp_f}°F</h1>
<TemperatureAndDetails />
<h1>Feels Like: {weather.current.feelslike_f}°F</h1>
<h1>Humidity: {weather.current.humidity}%</h1>
<h1>Wind Speed: {weather.current.gust_mph} mph</h1>
</div>
);
}
async function getWeather() {
const response = await fetch(
"https://api.weatherapi.com/v1/current.json?key=462eaa5d277d46b0957222907232503&q=London&aqi=no"
);
return response.json();
}
export default App;