[英]React-native: undefined is not an object
Probably it's a newbie question... I get a json response with an object from a fetch() running into a function on componentDidMount(). 可能这是一个新手问题...我从运行在componentDidMount()上的函数的fetch()中得到一个对象的json响应。 The result is saved into a state
结果保存到状态
data:
{
id: 1,
name: 'joseph',
tickets:
[
{id: 334, descripton: 'example1'},
{id: 768, descripton: 'example2'},
],
}
I need to list this array "tickets" in render (). 我需要在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>
)
}
But the "first return" is "undefined", generating error and then the state changes to the correct result. 但是“第一个返回”是“未定义的”,产生错误,然后状态变为正确的结果。 The fetch is running with async await, but still show the "undefined" first.
提取正在异步等待状态下运行,但仍会先显示“未定义”。
The console.log show 2 results: one "undefined" and another with the result. console.log显示2个结果:一个为“未定义”,另一个为结果。
Any good soul to help me, please? 有什么好的灵魂可以帮助我吗?
It's because at the start this.state.data.tickets is undefined and you are calling it in the render function which is not gonna wait until this.getFetch() finishes. 这是因为在开始时this.state.data.tickets是未定义的,而您是在render函数中调用它的,它不会等到this.getFetch()完成。 So.. you can do a conditional rendering to check if this.state.data.tickets exist in rendering
因此,您可以进行条件渲染以检查this.state.data.tickets是否在渲染中存在
replace {this.showTickets(this.state.data.tickets)}
替换
{this.showTickets(this.state.data.tickets)}
with {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!==undefined? this.showTickets(this.state.data.tickets) : null}
What we are doing here is first checking if this.state.data.tickets is not undefined. 我们在这里首先要检查this.state.data.tickets是否未定义。 While it is undefined (at the start) we return null, when it stops being undefined we call this.showTickets.
虽然它是未定义的(一开始),但我们返回null;当它不再是未定义的时,我们称为this.showTickets。
You can even initialize this.state.data as an empty array, and you can delete the part when we check if it's undefined since an empty array will return false 您甚至可以将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.