gpt4 book ai didi

javascript - Wordpress API,React : this. state.project.title 未定义

转载 作者:行者123 更新时间:2023-12-03 02:55:28 25 4
gpt4 key购买 nike

我正在开发一个包含后端 Wordpress 和前端 React 的项目。

但是当我尝试从 Json 数据获取 title.rendered 时,我有这个:

类型错误:this.state.project.title 未定义

我可以看到数据存在于 React Web 扩展中:

截图:

enter image description here

所以我不知道为什么会出现这个错误。

这是我的代码,感谢您的帮助;):

import React, { Component } from 'react';
import {LoadingSpin} from "./LoadingSpin";

export class Project extends Component {
constructor(){
super();
this.state = {
project: [],
loading: true
}
}
componentDidMount() {
let dataURL = "http://api.florentbruziaux.com/wp-json/wp/v2/portefolio_projects/"+ this.props.match.params.id + "?_embed";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
project: res,
loading:false
})
});



}
render(){
let ahah = this.state.project.title.rendered;
console.log(ahah);

return (
<div>
{ (this.state.loading) ? <LoadingSpin/> : null}
<h1 className="title"> </h1>
</div>
);
}

}

最佳答案

componentDidMount()在组件安装后调用,因此在调用之前有一个初始渲染。在第一次调用 render 时,不会加载 project。你需要处理这个案子。您已经拥有 state.loading,因此当 loading 为 true 时,请勿尝试访问 project 上的任何内容。

关于javascript - Wordpress API,React : this. state.project.title 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com