You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中遍历JSON的city数组实现联动下拉框问题求助

解决React国家-城市联动下拉框的显示问题

我来帮你搞定这个联动下拉的问题!你目前遇到的问题主要有两个核心原因,咱们一步步修正:

问题分析

  1. setState的异步特性:你在onChangeHandler里设置selectedCity时用了this.state.selectedCountry.city,但setState是异步更新状态的,这时候this.state.selectedCountry还没变成刚选中的国家数据,自然拿不到正确的城市数组。
  2. 下拉框渲染错误:第二个下拉框没有遍历城市数组生成独立的选项,而是直接把整个数组作为单个option的内容,所以会显示成数组字符串。

修正后的完整代码

export default class DiffCountries extends Component { 
  constructor(props) { 
    super(props); 
    this.state = { 
      isLoading: true, 
      contacts: [], 
      selectedCountry: null, // 初始化为null更合理
      selectedCity: [] 
    } 
  } 

  onChangeHandler = (event) => { 
    const selected = CountriesData[event.target.value - 1]; 
    // 直接用选中的国家数据里的city数组,不要依赖state的异步更新
    this.setState({ 
      selectedCountry: selected, 
      selectedCity: selected.city 
    }); 
  } 

  render() { 
    const { selectedCity } = this.state; 
    return ( 
      <div> 
        <select onChange={this.onChangeHandler}> 
          {CountriesData.map(item => { 
            const { id, country } = item; 
            return <option key={id} value={id}>{country}</option> 
          })} 
        </select> 

        <select> 
          {/* 遍历selectedCity数组生成每个城市的选项 */}
          {selectedCity.length > 0 ? (
            selectedCity.map((city, index) => (
              <option key={index} value={city}>{city}</option>
            ))
          ) : (
            <option value="">请先选择国家</option>
          )}
        </select> 
      </div> 
    ) 
  } 
}

关键修正点说明

  • 状态初始化:把selectedCountry初始化为null,避免初始状态下的类型判断混乱;
  • onChangeHandler优化:直接使用刚获取到的选中国家对象selected来设置selectedCity,绕开setState的异步问题;
  • 第二个下拉框渲染:通过map遍历selectedCity数组,为每个城市生成独立的<option>标签,这样就能正常显示每个城市选项了。

内容的提问来源于stack exchange,提问作者Opie Winston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:46:01