简体   繁体   English

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

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

I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error : 我希望来自远程服务器的一些数据能够在屏幕上显示出来,但是我在模拟器中遇到此错误。 Cannot read property 'undefined' of undefined原因是在到达结果之前呈现内容的原因,这是我遇到此错误的代码:

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

So the property caption is expecting a text, and to deal with undefined values I added this || '---Choose---' 因此,属性caption需要一个文本,并且为了处理未定义的值,我在此添加了|| '---Choose---' || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined) || '---Choose---'在出现null的情况下显示文本'---Choose---' ,但问题是this.state.dropDownSelectedItems['gender']未定义,并且当this.state.customFieldDropdown访问该this.state.customFieldDropdown时值导致错误(读取未定义的属性)

So how to deal with this issue? 那么该如何处理呢?

You seems to have undefined value higher in the property chain. 您似乎在属性链中的不确定值更高。 The || || operator will match only last value in the chain, so if for example this.state.customFieldDropdown['gender'] is undefined it will fail. 运算符将仅匹配链中的最后一个值,因此,例如,如果未定义this.state.customFieldDropdown['gender'] ,它将失败。

I'll suggest you to take a look at idx function introduced by React team. 我建议您看一下React团队介绍的idx函数。 More details here: https://facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html 此处有更多详细信息: https : //facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html

Idx is really good. Idx真的很好。 You can do something like that: 您可以执行以下操作:

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