反应:无法访问渲染函数内部状态存储的数组的属性

时间:2018-11-30 17:50:20

标签: reactjs

登录控制台时,来自API调用的响应已保存到状态。

.then(response => {
        this.setState({
            transactions: response,
        })
        if(this.state.transactions.meta.total > 0){
            console.log(this.state.transactions.data[0].id)
        }


    })

但是在渲染函数中调用

this.state.transactions.meta.total > 0
?
<tbody>
  {
    this.state.transactions.data.map((transactions) => 
    <tr key={transactions.id}>
      <td>{transactions.status}</td>
      <td>{`${transactions.currency} ${transactions.amount / 100} from ${transactions.customer.email}`}</td>
      <td>{transactions.paid_at}</td>
    </tr>
    )
  }
</tbody>
:
<tbody>
  <tr>
    <td colSpan="3">There are no transactions at the moment</td>
  </tr>
</tbody>

它不起作用。我怎么可能出问题了?

1 个答案:

答案 0 :(得分:0)

设置加载状态:

state = {
 loading: true
}

异步调用完成后,将加载设置为false:

.then(response => {
        this.setState({
            transactions: response,
            loading: false
        })
        if(this.state.transactions.meta.total > 0){
            console.log(this.state.transactions.data[0].id)
        }


    })

仅在渲染为false时才渲染:

!this.state.loading
?
<tbody>
  {
    this.state.transactions.data.map((transactions) => 
    <tr key={transactions.id}>
      <td>{transactions.status}</td>
      <td>{`${transactions.currency} ${transactions.amount / 100} from ${transactions.customer.email}`}</td>
      <td>{transactions.paid_at}</td>
    </tr>
    )
  }
</tbody>
:
<tbody>
  <tr>
    <td colSpan="3">Loading..</td>
  </tr>
</tbody>