React天气项目:如何将输入框值传递给提交按钮并赋值给cityName
React天气查询代码修改建议
以下是针对你的需求需要调整的几个关键点:
- 合并冗余状态:删除单独的
value状态,直接用cityName绑定输入框,减少不必要的状态维护。 - 修复useEffect无限循环问题:给useEffect添加依赖数组
[cityName],只有当cityName变化时才触发天气查询请求。 - 完善天气状态更新:获取到天气数据后,调用
setCityWeather将数据存入状态,方便后续渲染使用。 - 设置输入框为受控组件:给输入框添加
value={cityName}属性,确保输入框内容和状态保持同步。
修改后的完整代码:
import { useState, useEffect } from "react" export function WeatherInfo() { const token: string = '7ebe7c2a03cd48c090a193437' async function getCurrentWeather(cityName: string): Promise<any> { const response = await fetch(`http://api.weatherapi.com/v1/current.json?key=${token}&q=${cityName}`) const data = await response.json() console.log(data) return data } const [cityName, setCityName] = useState('') const [cityWeather, setCityWeather] = useState({}) const handleChange = (event: any) => { setCityName(event.target.value) } const handleSubmit = (event: any) => { event.preventDefault() // 提交时cityName已通过handleChange更新,useEffect会自动监听cityName变化触发查询 } useEffect(() => { // 城市名称为空时不发起请求 if (!cityName) return async function fetchData() { const weatherData = await getCurrentWeather(cityName) setCityWeather(weatherData) } fetchData() }, [cityName]) return ( <div > <form onSubmit={handleSubmit}> <input onChange={handleChange} value={cityName} placeholder="输入城市名称" /> <button>查询天气</button> </form> {/* 可添加天气数据渲染示例 */} {Object.keys(cityWeather).length > 0 && ( <div> <h3>{cityWeather.location.name}</h3> <p>温度:{cityWeather.current.temp_c}°C</p> <p>天气:{cityWeather.current.condition.text}</p> </div> )} </div> ); }
内容的提问来源于stack exchange,提问作者Alex_Lima84
相关产品推荐
相关产品推荐

