使用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