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

React中API数据匹配异常求助:输入County无法正确返回对应Area

问题分析与修复

你的代码核心问题出在Array.find()的使用逻辑上,导致无论输入什么都会匹配数组第一个元素:

  • 你在find回调里写了({ enteredValue }) => enteredValue === Stations.county,这里的({ enteredValue })是尝试解构数组元素的enteredValue属性,但你的Stations元素里只有county、area等属性,没有enteredValue,所以这个变量会是undefined;同时Stations.county是访问数组本身的county属性,数组没有这个属性,结果也是undefined。两个undefined相等,所以find直接返回了数组第一个元素。
  • 另外,newdata.map()是同步操作,不需要加await,data.items也不需要await,因为它是已解析JSON里的直接属性。

修复后的代码

import './App.css';
import { useRef } from 'react';

function App() {
  const nameInputRef = useRef();

  async function fetchData() {
    const enteredValue = nameInputRef.current.value.trim();
    if (!enteredValue) {
      console.log('请输入县名');
      return;
    }

    try {
      const response = await fetch(
        'https://environment.data.gov.uk/flood-monitoring/id/floodAreas'
      );
      if (!response.ok) {
        throw new Error('请求失败');
      }
      const data = await response.json();
      const newdata = data.items;
      const Stations = newdata.map(value => ({
        id: value.fwdCode,
        county: value.county,
        area: value.eaAreaName,
        label: value.label,
        polygon: value.polygon,
        loc: value.riverOrSea,
      }));

      // 正确匹配用户输入的county
      const result = Stations.find(item => item.county === enteredValue);
      if (result) {
        console.log(result.area);
      } else {
        console.log('未找到匹配的县');
      }
    } catch (error) {
      console.error('发生错误:', error);
    }
  }

  return (
    <div className="App">
      <section>Input your County</section>
      <br />
      <input type="text" ref={nameInputRef}></input>
      <br />
      <button onClick={fetchData}>Show data here..</button>
    </div>
  );
}
export default App;

关键修改说明

  • 修正find回调逻辑:直接拿数组元素的county属性和用户输入的enteredValue对比,精准匹配目标元素。
  • 移除多余的await:同步操作无需异步等待,优化代码执行逻辑。
  • 添加基础验证与错误处理:
    • 检查用户输入是否为空
    • 校验请求响应状态
    • 处理无匹配结果的情况
    • 捕获异步流程中的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:52:53