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

React JS:如何仅展示选中国家对应的州?现有代码显示全部州

解决只显示选中国家对应州的问题

要实现仅展示选中国家的州,你需要先添加国家选择器并维护选中状态,再根据选中的国家过滤对应州数据,具体修改如下:

1. 添加国家选择器并维护选中状态

假设你使用React,先在组件内添加选中国家的状态,再渲染国家选择下拉框:

import { useState } from 'react';

// 组件内部状态
const [selectedCountryId, setSelectedCountryId] = useState('');

// 渲染国家选择框
<select 
  name="country" 
  value={selectedCountryId}
  onChange={(e) => setSelectedCountryId(e.target.value)}
>
  <option value="">--Select country--</option>
  {state.map((country, idx) => (
    <option key={idx} value={country.id}>{country.name}</option>
  ))}
</select>

2. 修改州选择框的渲染逻辑

根据选中的国家ID,过滤出对应国家的州数据再渲染:

<select name="state">
  <option>--Select state--</option>
  {selectedCountryId && (
    // 匹配选中国家,取出对应州列表
    state.find(country => country.id === selectedCountryId)
      ?.data[0]
      ?.states.map((stateItem, index) => (
        <option key={index}>{stateItem.name}</option>
      ))
  )}
</select>

逻辑说明

  • 通过国家选择框获取用户选中的国家ID,存储在selectedCountryId状态中
  • 用户选中国家后,用find方法从你的state数组中匹配对应国家对象
  • 用可选链(?.)避免找不到数据时触发报错,确保仅找到对应国家时才渲染其下属州
  • 未选中任何国家时,州选择框仅显示默认提示选项

内容的提问来源于stack exchange,提问作者Divya Agarwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:45:34