簡體   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