[英]React-native: undefined is not an object
可能這是一個新手問題...我從運行在componentDidMount()上的函數的fetch()中得到一個對象的json響應。 結果保存到狀態
data:
{
id: 1,
name: 'joseph',
tickets:
[
{id: 334, descripton: 'example1'},
{id: 768, descripton: 'example2'},
],
}
我需要在render()中列出此數組“門票”。
componentDidMount(){
this.getFetch(...);
}
showTickets(WTickets){
console.log(WTickets);
WTickets.map((item)=>{
return (item.id)
})
}
render(){
return(
<View>
{this.showTickets(this.state.data.tickets)}
</View>
)
}
但是“第一個返回”是“未定義的”,產生錯誤,然后狀態變為正確的結果。 提取正在異步等待狀態下運行,但仍會先顯示“未定義”。
console.log顯示2個結果:一個為“未定義”,另一個為結果。
有什么好的靈魂可以幫助我嗎?
這是因為在開始時this.state.data.tickets是未定義的,而您是在render函數中調用它的,它不會等到this.getFetch()完成。 因此,您可以進行條件渲染以檢查this.state.data.tickets是否在渲染中存在
替換{this.showTickets(this.state.data.tickets)}
與{this.state.data!==undefined? this.showTickets(this.state.data.tickets) : null}
{this.state.data!==undefined? this.showTickets(this.state.data.tickets) : null}
我們在這里首先要檢查this.state.data.tickets是否未定義。 雖然它是未定義的(一開始),但我們返回null;當它不再是未定義的時,我們稱為this.showTickets。
您甚至可以將this.state.data初始化為一個空數組,並且當我們檢查該部分是否未定義時可以刪除它,因為一個空數組將返回false
constructor() {
super();
this.state = {
data: []
};
}
....
....
//in render function
{this.state.data? this.showTickets(this.state.data.tickets) : null}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.