React下拉菜单任务求助:无法获取州级API数据
问题分析与修复方案
你的代码存在几个核心问题导致无法获取州级数据:
- 未跟踪选中的国家值:你用整个
countries数组作为第二个useEffect的依赖,而不是用户实际选中的国家代码。数组变化只会在初始加载时触发,选择国家时不会触发该副作用。 - 下拉菜单缺少
onChange事件:国家选择框没有绑定事件处理函数,无法捕获用户的选择操作。 - Option未设置
value属性:每个国家选项没有指定对应country_code作为value,导致无法获取正确的API参数。 - 错误的条件判断:
countries是数组类型,判断countries === 'default' || countries === ''永远不会成立。
修复后的完整代码
import { useState, useEffect } from "react"; const CountriesStates = () => { const [countries, setCountries] = useState([]); const [states, setStates] = useState([]); // 新增状态跟踪选中的国家代码 const [selectedCountryCode, setSelectedCountryCode] = useState(''); useEffect(() => { fetch('https://xc-countries-api.fly.dev/api/countries/') .then((response) => response.json()) .then((data) => setCountries(data)) .catch(err => console.error('获取国家数据失败:', err)); }, []); // 依赖改为选中的国家代码,只有当选中值变化时才触发 useEffect(() => { if (!selectedCountryCode) { setStates([]); return; } fetch(`https://xc-countries-api.fly.dev/api/countries/${selectedCountryCode}/states/`) .then((response) => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then((data) => setStates(data)) .catch(err => console.error('获取州数据失败:', err)); }, [selectedCountryCode]); // 处理国家选择变化的函数 const handleCountryChange = (e) => { setSelectedCountryCode(e.target.value); }; return ( <> <div> <select name='countries' id='countries' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}} value={selectedCountryCode} onChange={handleCountryChange} > {/* 新增默认选项 */} <option value="">请选择国家</option> {countries.map((country) => ( <option key={country.id} value={country.country_code}> {country.name} </option> ))} </select> </div> <div> <select name='states' id='states' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}} disabled={!selectedCountryCode} > <option value="">请选择州/省</option> {states.map((state) => ( <option key={state.id} value={state.id}> {state.name} </option> ))} </select> </div> </> ); }; export default CountriesStates;
关键修复点说明
- 新增
selectedCountryCode状态:专门跟踪用户选中的国家代码,作为请求州数据的参数。 - 绑定
onChange事件:通过handleCountryChange函数更新选中状态,触发后续的API请求。 - 设置Option的
value:将country.country_code作为选项值,确保能获取到正确的API路径参数。 - 修正副作用依赖:第二个
useEffect依赖selectedCountryCode,只有当选中值变化时才发起州数据请求。 - 添加错误处理:在fetch中加入
catch捕获请求异常,方便调试。 - 优化用户体验:添加默认选项,州下拉框在未选国家时禁用。
内容的提问来源于stack exchange,提问作者Onur Alemdaroglu
相关产品推荐
相关产品推荐

