React组件间数据传递问题:天气API请求400错误求助
解决方案:React组件间数据传递(Search → App)
核心问题是子组件(Search)向父组件(App)传递数据,React中标准的做法是使用回调函数,以下是具体实现步骤和代码示例:
1. 在App组件中定义状态与回调函数
首先在App组件里维护城市名称的状态,并写一个接收子组件传递数据的回调函数:
import { useState, useEffect } from 'react'; import Search from './Search'; import CurrentWeather from './CurrentWeather'; import FiveDayForecast from './FiveDayForecast'; function App() { // 存储选中的城市名 const [targetCity, setTargetCity] = useState(''); // 回调函数:接收Search组件传递的城市名 const handleCitySubmit = (cityName) => { setTargetCity(cityName.trim()); }; // 当城市名变化时,发起API请求 useEffect(() => { if (!targetCity) return; // 替换成你的OpenWeather API密钥 const apiKey = '你的API_KEY'; const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${targetCity}&appid=${apiKey}`; fetch(weatherUrl) .then(res => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .then(data => { console.log('天气数据:', data); // 这里可以将数据传递给天气组件展示 }) .catch(err => console.error('API请求错误:', err)); }, [targetCity]); return ( <div className="weather-app"> <Search onCitySubmit={handleCitySubmit} /> {targetCity && ( <> <CurrentWeather city={targetCity} /> <FiveDayForecast city={targetCity} /> </> )} </div> ); } export default App;
2. 在Search组件中调用回调函数传递数据
Search组件通过props接收回调函数,在用户提交输入时调用该函数,把输入的城市名传回App:
import { useState } from 'react'; function Search({ onCitySubmit }) { const [inputVal, setInputVal] = useState(''); const handleFormSubmit = (e) => { e.preventDefault(); if (inputVal.trim()) { // 调用父组件传来的回调函数,传递输入值 onCitySubmit(inputVal); setInputVal(''); // 清空输入框 } }; return ( <form onSubmit={handleFormSubmit} className="search-form"> <input type="text" value={inputVal} onChange={(e) => setInputVal(e.target.value)} placeholder="输入城市名..." /> <button type="submit">搜索</button> </form> ); } export default Search;
关键注意事项
- 确保调用回调函数时传递的是有效输入值(比如先trim去除空格,避免空字符串传递)
- API请求要放在
useEffect中,依赖项设为targetCity,确保只有城市名变化时才发起请求 - 调试时可以在
handleCitySubmit中添加console.log(cityName),确认子组件是否正确传递了数据
学习建议
- 吃透React的单向数据流规则:父→子靠props,子→父靠回调函数,这是组件通信的基础
- 练习
useState和useEffect的配合使用,理解状态变化如何触发副作用(比如API请求) - 养成调试习惯:用
console.log追踪状态值、props传递情况,检查API请求URL的参数是否正确
内容的提问来源于stack exchange,提问作者Angelo4B3
相关产品推荐
相关产品推荐

