React天气应用输入框仅能输入单个字符后刷新表单求助
天气应用输入框输入单个字符后刷新的问题解决
核心问题与修复方案
1. 表单默认提交行为导致页面刷新
表单提交时浏览器会默认刷新页面,这是你输入内容丢失的主要原因。需要在提交函数中阻止默认行为:
const fetchWeather = async (e) => { e.preventDefault(); // 阻止页面刷新 const response = await axios.get( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}` ); updateWeather(response.data); };
2. 模板字符串语法错误
你用了双引号包裹URL,里面的${city}和${API_KEY}不会被解析为变量,必须改用反引号`:
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`
3. 输入框未与状态绑定
输入框没有绑定value到city状态,会导致输入时状态与输入框内容不同步,引发渲染异常:
<input placeholder="City" onChange={(e)=> updateCity(e.target.value)} value={city} // 绑定状态到输入框 />
4. 状态初始值未定义
city状态初始值为undefined,建议设为空字符串避免潜在问题:
const [city, updateCity] = useState("");
完整修正代码
App.js
import axios from "axios"; import { useState } from "react"; import "./App.css"; import CityComponent from "./CityComponent"; import WeatherComponent from "./WeatherComponent"; import styled from "styled-components"; const API_KEY = "42d13a711450b30b23cab2b8a7b34e7c"; function App() { const [city, updateCity] = useState(""); const [weather, updateWeather] = useState(); const fetchWeather = async (e) => { e.preventDefault(); try { const response = await axios.get( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}` ); updateWeather(response.data); } catch (err) { alert("未找到该城市,请检查输入"); } }; return ( <Container> <AppLabel>weather app</AppLabel> {weather ? ( <WeatherComponent /> ) : ( <CityComponent updateCity={updateCity} fetchWeather={fetchWeather} /> )} </Container> ); } export default App
CityComponent.jsx
import React from "react"; const CityComponent = ({ updateCity, fetchWeather, city }) => { return ( <> <img src="/icons/perfect-day.svg" alt="晴天图标" className="Perfectday" /> <ChooseCityLabel>查询你所在城市的天气</ChooseCityLabel> <SearchBox onSubmit={fetchWeather}> <input placeholder="City" onChange={(e) => updateCity(e.target.value)} value={city} /> <button type="submit">搜索</button> </SearchBox> </> ); }; export default CityComponent;
内容的提问来源于stack exchange,提问作者Sneha Barua
相关产品推荐
相关产品推荐

