【问题标题】:React.js, pulling data from api and then looping through to displayReact.js,从api中拉取数据然后循环显示
【发布时间】:2018-05-11 01:33:11
【问题描述】:

我是新手。我正在尝试从 API 中提取数据,然后循环并显示它。 错误:无法读取未定义的属性“地图”。

API 数据正在通过,但似乎 React 在数据存储到 State 之前调用了循环列表。

  constructor () {
super()
this.state = {
  data:'',
}

}

componentWillMount(){
 // Im using axios here to get the info, confirmed data coming in. 

//更新“数据”状态以等于来自 api 调用的响应数据。

}

loopListings = () => {
   return this.state.data.hits.map((item, i) => {
     return(<div className="item-container" key={i}>
      <div className="item-image"></div>
      <div className="item-details">tssss</div>
      </div>)
    })
  }

  loopListings = () => {
return this.state.data.hits.map((item, i) => {
  return(
    <div className="item-container" key={i}>
      <div className="item-image"></div>
      <div className="item-details">tssss</div>
    </div>)
})


 }


  render () {
    return (
      <div>
          {this.loopListings()}

      </div>
        )
      }

【问题讨论】:

  • 在你的数据进来之前,它只是一个字符串。字符串不具有属性hits。您应该在映射之前检查它是否存在或将初始状态设置为data: { hits: [] }
  • 看来我需要阅读更多关于生命周期的内容。我的印象是 componentWillMount 会在渲染之前运行。我正在使用 componentWillMount 区域内的 api 响应数据更新空数据状态。

标签: reactjs


【解决方案1】:

您收到此错误的原因是您对 API 的调用与反应生命周期方法异步发生。当 API 响应返回并持续到状态时,render 方法已经被第一次调用并且由于您试图访问尚未定义的对象上的属性而失败。

为了解决这个问题,您需要确保在 API 响应被持久化到状态之前,render 方法不会尝试访问您的渲染方法中的那部分状态,或者确保如果它这样做了构造函数中有一个有效的默认状态:

通过改变你的渲染来解决这个问题:

render () {
    return (
      <div>
      {this.state.data && 
        Array.isArray(this.state.data.hits) 
         && this.loopListings()}
      </div>
        )
      }

或者像这样初始化你的构造函数:

constructor () {
      super()
      this.state = {
       data: {hits: []},
      }
    }

记住 react 只是 javascript,它的行为是一样的。

【讨论】:

  • 感谢您的澄清。答案 #1 本质上是一个布尔值,一旦全部为真,它将运行。答案 #2:在这种情况下,由于异步,我的列表加载为空,然后在 axios 调用完成状态更改时重新渲染,现在显示我的列表?
【解决方案2】:

您可以检查desir data.hits 是否存在于状态中。

{this.state.data && Array.isArray(this.state.data.hits) ? 
     this.loopListings()
     : null}

还要确保,在检索到数据后调用 this.setState 方法,如下所示。

this.setState({ data })

【讨论】:

  • 您可以通过检查类型来摆脱额外的长度检查(并摆脱null,只使用&amp;&amp;)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多