【问题标题】:this.state.item.id is undefned. react-nativethis.state.item.id 未定义。反应式
【发布时间】:2020-03-29 18:50:49
【问题描述】:

从 API 解析一些单独的结果后,我遇到了这个问题。

我将值分配给我的数组:

this.setState({
   item: responseJson.items,
});

但是当我尝试在视图中渲染其结果之一时,什么都不会渲染,并且在日志中显示为 undefined

我尝试做的是:{this.state.item.id}

我得到的json示例:

{"items":[{"id":"17228","strItem":"Toy", etc. etc.

如何渲染 id

在渲染上 <Text>{this.state.item.id}</Text>

提前致谢。

【问题讨论】:

  • 还添加了渲染功能
  • this.state.item 是一个数组
  • 您应该使用this.state.item[i].id 访问您想要的元素,其中i 是元素的索引。
  • this.state.item[0].id
  • @MoshFeu 通过这样做我得到了undefined is not an object

标签: javascript react-native


【解决方案1】:

您的this.state.item 是一个数组。

如果你想获取项目,你应该使用[] 语法。

const firstItem = this.state.item[0];
const firstItemId = firstItem.id;

如果要通过id获取数组项:

const desiredItem = this.state.item.find(item => item.id === desiredId);

检查:

if (Array.isArray(this.state.item) && this.state.item.length > 0) {
  console.log(this.state.item[0]);
}

【讨论】:

  • 如果我使用this.state.item[0].id,我会得到undefined is not an object
  • @DanielLogvin 我这是因为您没有立即拥有您的物品。尝试使用if 语句。我会更新答案
  • 它可能默认为一个空数组...我们需要您的问题@DanielLogvin 中的更多信息
  • 我添加了长度检查
【解决方案2】:

正确的解决方案是映射它。

解决方案代码:

{this.state.fontLoaded && this.state.item.map(it => {
return (
<Text>ID: {it.id}</Text>
)
})}

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 2014-09-18
    • 2018-07-06
    • 1970-01-01
    • 2021-09-20
    • 2018-05-20
    • 2019-04-27
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多