简体   繁体   中英

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 :

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---' || '---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)

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.

I'll suggest you to take a look at idx function introduced by React team. More details here: https://facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html

Idx is really good. 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---'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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