Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')

Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')

我是 React 的新手,正在尝试制作一个无头的 worpdpress 应用程序。 当我获取 post 时,我只得到第一个值。

我获取 post 并将其保存在状态

componentDidMount() {
this.setState({ loading: true }, () => {
  axios.get('http://localhost/wpprojekte/ebike/wp-json/wp/v2/posts/426')
    .then(res => {
      this.setState({ loading: false, error: 'no error', post: res.data })
    }).catch(error => {
      console.log(error);
    });
});}

我现在 post 在我的状态下看起来像

constructor(props) {
super(props);
this.state = {
  loading: false,
  error: 'error',
  post: {},
}}

当我渲染组件时,我只能从 post 中获取第一个值。 例如 this.state.post.date

当我尝试获取 this.state.post.title.rendered

Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')

这里是渲染函数

render() {
console.log(JSON.stringify(this.state.post));
return (
  <div>
    {<div dangerouslySetInnerHTML={{ __html: this.state.post.title.rendered }} />}
  </div>
)}

我不明白为什么它只得到第一个值。

这是控制台日志

  "id": 426,
  "date": "2021-05-07T09:49:37",
  "date_gmt": "2021-05-07T09:49:37",
  "guid": {
    "rendered": "http://localhost/wpprojekte/ebike/?post_type=genusstouren&#038;p=426"
  },
  "modified": "2021-11-30T11:00:28",
  "modified_gmt": "2021-11-30T11:00:28",
  "slug": "schoeningen-helmstedt",
  "status": "publish",
  "type": "genusstouren",
  "link": "http://localhost/wpprojekte/ebike/genusstouren/schoeningen-helmstedt/",
  "title": {
    "rendered": "Genuss Bike Paradies Etappe 10"
  },
  "content": {
    "rendered": "\n<p><strong>Diese Etappe startet in Schöningen und führt am Lappwaldsee durch Helmstedt und den angrenzenden Lappwald nach Wolfsburg.</strong></p>\n\n\n\n<p>Die Route beginnt am Burgplatz nahe des Schlosses Schöningen und führt am ehemaligen Tagebau entlang in Richtung Norden. Dort führt die Tour westlich am Lappwaldsee entlang nahe des Grenzübergangs Helmstedt/Marienborn, welcher der größte und bedeutendste Grenzübergang an der innerdeutschen Grenze war. Von Helmstedt aus, in dessen Altstadt noch immer Teile der Stadtmauer als Wallanlagen zu finden sind, folgt die Route dem Lappwald, führt durch bewaldetes Gebiet und am Kloster Mariental durch Grasleben wieder in westlichere Richtung. Über Feldwege und durch kleinere Ortschaften geht es nach Velpke und von dort aus durch die Velpker Schweiz nach Oebisfelde. Nach Grafhorst und Überquerung der Aller führt die Route am Naturschutzgebiet Wendschotter und Vorsfelder Drömling entlang nach Wolfsburg, wo die Etappe am Wissenschaftsmuseum phaeno endet.</p>\n\n\n\n<p></p>\n\n\n\n<script type=\"text/javascript\" src=\"https://regio.outdooractive.com/oar-harz/de/embed/55540446/js?mw=false\"></script>\n",
    "protected": false
  },
  "excerpt": {
    "rendered": "<p>Diese Etappe startet in Schöningen und führt am Lappwaldsee durch Helmstedt und den</p>\n<div class=\"mehr-erfahren\"><a href=\"http://localhost/wpprojekte/ebike/genusstouren/schoeningen-helmstedt/\" rel=\"nofollow\"><icon class=\"fas fa-angle-double-right\"></icon> mehr erfahren</a></div>\n",
    "protected": false
  },
  "author": 2,
  "featured_media": 442,
  "parent": 0,
  "menu_order": 0,
  "template": "",
  "meta": [],
  "featured_image_src": "http://localhost/wpprojekte/ebike/wp-content/uploads/2021/05/Etappe_10.jpg",
  "_links": {
    "self": [
      {
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/genusstouren/426"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/genusstouren"
      }
    ],
    "about": [
      {
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/types/genusstouren"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/users/2"
      }
    ],
    "version-history": [
      {
        "count": 3,
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/genusstouren/426/revisions"
      }
    ],
    "predecessor-version": [
      {
        "id": 1065,
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/genusstouren/426/revisions/1065"
      }
    ],
    "wp:featuredmedia": [
      {
        "embeddable": true,
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/media/442"
      }
    ],
    "wp:attachment": [
      {
        "href": "http://localhost/wpprojekte/ebike/wp-json/wp/v2/media?parent=426"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

解决方案

您收到错误的原因是因为 componentDidMount 在您的渲染方法被调用之后被调用,即您的 UI 在您的 post 之前被渲染已获取,它与错误有何关系?现在就是这样。从你的代码调用 this.state.post.date returns null 是空的并且不会引起任何问题,因为来自 react lifecycle render 方法是在 componentDidMount 之前首先调用,但在未获取 post 或状态不可用时调用 this.state.post.title.rendered 执行以下操作,首先它检查 this.state.post.title 是 null,它可以作为日期的 null 但调用 .rendered 现在将抛出 null你得到的错误。为确保您不会遇到此类错误,您必须确保已定义标题或在状态

上设置了 post

代码解决方案

用这个替换你的渲染。

render() {
return (
  <div>
    {
      this.state.post.title && (
      <div dangerouslySetInnerHTML={{ __html: this.state.post.title.rendered }} />)
    }
  </div>
)}