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

React中如何实现选中下拉框国家后展示data.json对应详情

问题原因

  1. 类型不匹配:下拉框<option>的value绑定的是数字类型的国家id,但e.target.value读取到的是字符串类型,全等判断countryObject.id === country永远为false,无法匹配到对应国家
  2. 数组遍历方法使用不当:匹配对应国家用map不合适,map是用来遍历生成新数组的,匹配单条数据应该用find方法更高效
  3. selectedCountry初始值不合理:初始设为字符串"id",后续存储对象的话初始值应该设为null或者空对象

修正后的完整代码(CountryUI.js)

import React from "react";
import { useState, useEffect } from "react";
import { connect } from "react-redux";
import { countryList } from "../actions";

const CountryUi = (props) => {
  useEffect(() => {
    props.countryList();
  }, []);

  const [countryId, setCountryId] = useState("");
  const [selectedCountry, setSelectedCountry] = useState(null);

  const selectHandleChange = (e) => {
    const id = e.target.value;
    setCountryId(id);
    // 转成数字类型匹配id,用find查找对应国家
    const targetCountry = props.countries.find(item => item.id === Number(id));
    if(targetCountry) {
      setSelectedCountry(targetCountry);
    }
  };

  return (
    <div>
      <h4>选择下拉框中的国家查看对应详情</h4>
      <form className="dropdown-form">
        <label className="form-labels">选择国家:</label>
        <select className="select-opt" onChange={selectHandleChange} value={countryId}>
          <option value="">请选择国家</option>
          {props.countries.map((country) => {
            return <option key={country.id} value={country.id}> {country.name} </option>;
          })}
        </select>
      </form>
      {/* 渲染选中国家的全部关联详情 */}
      {selectedCountry && (
        <div className="country-detail">
          <p>国家名称:{selectedCountry.name}</p>
          <p>所属大洲:{selectedCountry.continent}</p>
          <p>排名:{selectedCountry.rank}</p>
          <p>国家ID:{selectedCountry.id}</p>
        </div>
      )}
    </div>
  );
};
const mapStateToProps = (state) => {
  return { countries: Object.values(state.countries) };
};
export default connect(mapStateToProps, { countryList })(CountryUi);

额外优化说明

  • 给下拉框的option加了key属性,符合React列表渲染规范
  • 新增了默认"请选择国家"的空选项,避免初始默认选中第一个国家的问题
  • 给select加了value属性绑定,变成受控组件,状态更可控

内容的提问来源于stack exchange,提问作者Akash khanapurkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:39:04