javascript - React-native:未定义不是对象
问题描述
可能这是一个新手问题......我得到一个json响应,其中一个来自fetch()的对象运行到componentDidMount()上的一个函数中。结果保存到状态
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>
)
}
但是“第一次返回”是“未定义的”,产生错误,然后状态变为正确的结果。fetch 正在异步等待运行,但仍然首先显示“未定义”。
console.log 显示 2 个结果:一个是“未定义”,另一个是结果。
请哪位好心人帮帮我?
解决方案
这是因为在开始时 this.state.data.tickets 是未定义的,并且您在渲染函数中调用它不会等到 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.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}
...
推荐阅读
- .net - GoDaddy 迁移到 Plesk Windows 主机后无法访问 .Net Framework 4 Web 服务
- python-3.x - 尝试将切片对象转换为字典时出现奇怪的错误
- sql - 创建函数以返回 json Postgresql 时出现语法错误
- java - 如何使用 Java 8 的 Stream API 将 ArrayList 的元素与另一个 ArrayList 的每个元素进行比较?
- android - 为 Firebase 存储文件创建 Firestore 数据库
- javascript - 电子对话框不保存文件
- r - 用于矩阵的函数?
- php - 如何在 Laravel 7 / PHP 7 中使用 RIJNDAEL 加密
- javascript - javascript中的括号符号如何访问对象的属性?
- python - 无法正确识别车牌(Python、OpenCv、Tesseract)