【发布时间】: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>
);
}
}
我尝试改用useState、useEffect,但问题是一样的。我的猜测是之前调用了render()函数,这就是为什么会出现问题,但是如何使API数据转到render()函数。
【问题讨论】:
-
嗨,Negant,检查我的解决方案,如果有帮助,请告诉我。