繁体   English   中英

反应本机如何处理无法读取未定义的属性“未定义”

[英]react native how to deal with Cannot read property 'undefined' of undefined

我希望来自远程服务器的一些数据能够在屏幕上显示出来,但是我在模拟器中遇到此错误。 Cannot read property 'undefined' of undefined原因是在到达结果之前呈现内容的原因,这是我遇到此错误的代码:

caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }

因此,属性caption需要一个文本,并且为了处理未定义的值,我在此添加了|| '---Choose---' || '---Choose---'在出现null的情况下显示文本'---Choose---' ,但问题是this.state.dropDownSelectedItems['gender']未定义,并且当this.state.customFieldDropdown访问该this.state.customFieldDropdown时值导致错误(读取未定义的属性)

那么该如何处理呢?

您似乎在属性链中的不确定值更高。 || 运算符将仅匹配链中的最后一个值,因此,例如,如果未定义this.state.customFieldDropdown['gender'] ,它将失败。

我建议您看一下React团队介绍的idx函数。 此处有更多详细信息: https : //facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html

Idx真的很好。 您可以执行以下操作:

if (idx(this.state, _ => _.customFieldDropdown.gender[_.dropDownSelectedItems.gender]))
    caption = this.state.customFieldDropdown.gender[this.state.dropDownSelectedItems.gender]
else
    caption = '---Choose---'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM