首页 > 解决方案 > 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 个结果:一个是“未定义”,另一个是结果。

请哪位好心人帮帮我?

标签: javascriptreact-nativeundefined

解决方案


这是因为在开始时 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}
...

推荐阅读