事件处理程序中的 React SetState 与模拟数据和来自 API 的数据的行为不同

React SetState in event handler behaves differently with data mocked and data from API

我在两个场景之间重现了完全相同的案例(相同的代码)。

  1. 模拟数据
  2. 从 API
  3. 请求数据

1) 模拟数据的案例 => https://codesandbox.io/s/select-demo-0e90s 按预期工作

模拟的数据如下

const [items] = React.useState([
  { id: "1", name: "First Element" },
  { id: "2", name: "Second Element" },
  { id: "3", name: "Third Element" }
]);

setSelectedName(item.name) => returns 项目名称正确

2) 带有 API 请求的案例(要允许请求 CORS 插件 Chrome 扩展必须激活)=> https://codesandbox.io/s/select-demo-71u7h

数据来自 action/index.js => fetchLeaguesList()

中的调用请求

League.js组件中

setSelectedLeagueName(item.name) => TypeError Cannot read 属性 'name' of undefined, item in this case is undefined

所以我的问题是为什么 item 在我的第二种情况下未定义?在这种情况下我该如何解决?

这是因为在第 19 行的 League.js 中你做了 const item = items.find(item => item.id === value);

但是从API返回的JSON模型不是由id属性形成的,而是league_id.

然后您应该将行更改为 const item = items.find(item => item.league_id == value);