如何解决使用React从WP REST API中获取“标题”
我正在尝试从Wordpress REST API中获取一些数据,以将其呈现在我的React App中。例如“标题”,“日期”和“内容”。这是我的代码:
class App extends React.Component {
constructor (props){
super(props);
this.state = {
title: {},date: "",content: {}
};
}
componentDidMount() {
return fetch(`https://example.com/wp-json/wp/v2/posts?per_page=100`)
.then((response) => response.json())
.then((responseJson) => {
const { title,date,content } = responseJson;
this.setState({ title,content });
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<div>
<h1> {this.state.title.rendered} </h1>
<h3> {this.state.date} </h3>
<p> {this.state.content.rendered} </p>
</div>
);
}
}
export default App;
但这给我的“标题”和“内容”都带来了以下错误:
TypeError: Cannot read property 'rendered' of undefined
我在这里做错什么以及如何解决此错误?
解决方法
首先,访问WordPress API需要身份验证参数,请确认。 示例:
Request: GET https://<domain-name>/wp-json/wp/v2/posts
Header: Authorization : Bearer <token>
冒着用获取API调用中的undefined
替换状态属性的风险。
试试看。将有助于捕获未定义的内容,并放置备用内容。
this.setState({
date,title: title || {rendered: false},content: content || {rendered: false}
});
,
此代码解决了该问题:
img_tag
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。