事件处理程序中的React SetState在模拟数据和来自API的数据的情况下表现不同。

问题描述 投票:0回答:1

我有两个方案之间重现完全相同的情况(相同的代码)。

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

1)带数据模拟的案例=> https:/codesandbox.iosselect-demo-0e90s。 行之有效

嘲讽的数据如下

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

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

2) 有API请求的情况下(要允许请求CORS插件的Chrome扩展必须激活) => https:/codesandbox.iosselect-demo-71u7h。

数据来自于一个调用请求,在 action/index.js => fetchLeaguesList()

League.js 组成部分

setSelectedLeagueName(item.name) =&gt.TypeError TypeError Cannot read property 'name' of undefined, item 在这种情况下是未定义的

所以我的问题是,为什么 item 在我的第二种情况下是未定义的?在这种情况下,我怎样才能修复它?

javascript reactjs react-hooks setstate
1个回答
1
投票

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

但从API传回的JSON模型并不是用以下方式形成的 id 财产,而是 league_id.

然后你应该把这行改为 const item = items.find(item => item.league_id == value);

© www.soinside.com 2019 - 2024. All rights reserved.