You need to enable JavaScript to run this app. React中如何使用find方法访问嵌套数组内的cities城市列表数据
优惠活动
大模型
产品
解决方案
定价
更多

React中如何使用find方法访问嵌套数组内的cities城市列表数据

错误原因

你调用DATA.countries.find()报错的核心原因是DATA本身是存储所有区域(欧洲、美国等)的数组,没有直接的countries属性,该属性仅挂载在每个区域的对象下,必须先定位到对应的区域,才能访问到该区域下的countries数组。


解决方法

  1. 首先确认你的路由配置已经同时声明了title和country两个动态参数,示例路由规则如下:
<Route path="/:title/:country" element={<CityList />} />
  1. 在城市列表页组件中,先同时从useParams取出title和country两个参数,先匹配对应区域,再从区域的countries数组中匹配对应国家,即可拿到嵌套的cities数组。

完整代码示例

const CityList = () => {
  // 同时获取两个路由参数
  const { title, country } = useParams();
  // 先匹配对应区域,toLowerCase做大小写兼容,避免参数小写、数据源大写匹配失败的问题
  const selectedRegion = DATA.find(d => d.title.toLowerCase() === title.toLowerCase());
  // 再从区域的countries数组中匹配对应国家,可选链?.避免找不到区域时报错
  const selectedCountry = selectedRegion?.countries.find(item => item.country === country);

  return (
    <div className="main">
      {selectedCountry ? (
        // 遍历渲染城市列表
        selectedCountry.cities.map(cityItem => (
          <div key={cityItem.id} className="city-item">
            {cityItem.city}
          </div>
        ))
      ) : (
        <div>未找到对应城市数据</div>
      )}
    </div>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:15:08