【问题标题】:Cannot get deeper to arrays and objects无法深入了解数组和对象
【发布时间】:2019-10-03 10:27:31
【问题描述】:

我正在寻找一些解释,为什么在componentDidMount() 函数中,api 从API 返回所有值,而在render() 函数中却没有。在渲染函数中,我只能像{this.state.home.title} 一样到达第一级,但{this.state.home.acf.hero_text [1] .text} 返回一个未定义的错误。

import React, {Component} from "react";
import '../styles/App.scss';

class Home extends Component {
  constructor() {
    super();
    this.state = {
      home: []
    }
  }

  async componentDidMount() {
    let homeUrl = await fetch("http://localhost:8080/wp-json/better-rest-endpoints/v1/page/strona-glowna");
    fetch(homeUrl)
    let json = await homeUrl.json();
     this.setState({
       home: json
     })
     console.log(this.state.home);
     console.log(this.state.home.acf.hero_tekst[1].tekst); // works fine !
  }

  render() {
    console.log(this.state.home.acf); // works fine !
    return (
      <div className="Home">
        Home
        <br/>
        {this.state.home.title} // works fine !
        {this.state.home.acf.hero_tekst[1].tekst} // trows an error: Cannot read property 'hero_tekst' of undefined
      </div>
    );
  }
}

我尝试改用useStateuseEffect,但问题是一样的。我的猜测是之前调用了render()函数,这就是为什么会出现问题,但是如何使API数据转到render()函数。

【问题讨论】:

  • 嗨,Negant,检查我的解决方案,如果有帮助,请告诉我。

标签: json reactjs api


【解决方案1】:

在 componentDidMount 之前渲染函数调用所以值 {this.state.home.acf.hero_tekst[1].tekst} 是未定义的,你必须像

这样写检查
{this.state.home.acf.hero_tekst && this.state.home.acf.hero_tekst[1].tekst } 

【讨论】:

  • 效果很好,谢谢!我只需要更改为:{this.state.home.acf &amp;&amp; this.state.home.acf.hero_tekst[1].tekst}
【解决方案2】:

componentDidMount 在初始渲染后执行。最初,您的状态是空的。

所以当你的组件第一次渲染时,它不会得到任何数据并抛出错误。然后你的componentDidMount 执行哪个集合的状态值,在这里你可以看到更新的状态。

你应该检查数据是否存在,

{this.state.home && this.state.home.title} 
{this.state.home.acf.hero_tekst && this.state.home.acf.hero_tekst[1].tekst}

【讨论】: