【问题标题】:Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')未捕获的类型错误:无法读取未定义的属性(读取“渲染”)
【发布时间】:2022-01-12 13:57:46
【问题描述】:

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

我获取帖子并将其保存在状态

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);
    });
});}

我现在的状态是这样的帖子

constructor(props) {
super(props);
this.state = {
  loading: false,
  error: 'error',
  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
      }
    ]
  }
}

【问题讨论】:

  • 您可以记录post 对象以查看其实际包含的内容吗?
  • 我使用了console.log(JSON.stringify(this.state.post));,它显示了我在浏览器中看到的对象。所以数据存在
  • 请编辑您的问题并添加此输出。也许你错过了什么。
  • 好的,我在代码 sn-p 中做到了

标签: javascript reactjs wordpress-rest-api headless-cms


【解决方案1】:

解决方案

您收到错误的原因是因为 componentDidMount 在您的渲染方法被调用之后被调用,即您的 UI 在您的帖子被获取之前被渲染,它与错误有什么关系?现在就是这样。从您的代码调用 this.state.post.date 返回 null ,它是空的并且不会导致任何问题,因为从 react 生命周期 渲染方法在 componentDidMount 但调用 this.state.post.title.rendered 当帖子未获取或状态不可用时会执行以下操作,首先它检查 this.state.post.title 这是 null ,它可以像日期一样工作,但是在 null 上调用 .rendered 现在会抛出你得到的错误。为确保您不会遇到此类错误,您必须确保已定义标题或将帖子设置为状态

代码解决方案

用这个替换你的渲染。

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

【讨论】:

  • 谢谢你,效果很好,this.props.match.params我也有同样的问题,总是未定义,难道也是同样的原因?
  • 您是否尝试访问 react-router-dom 中的路由参数?
  • 是的,这是我的路线 &lt;Route path="post"&gt;&lt;Route path=":postid" element={&lt;Post /&gt;} /&gt;&lt;/Route&gt; 我正在传递 id。在我的 MainComponent 中,我有一个链接可以转到单个 Post id &lt;Link id={post.id} to={{ pathname: "/post/"+post.id }}&gt;Read more&lt;/Link&gt; 我需要在 componentDidMount() 中获取这个参数(id)
  • path="post" 更改为 path="/post" 并将 path=":postid" 更改为 path="/:postid" 如果它不起作用,请发送您正在使用的 react-router dom 版本,以便我可以在演示中查看它反应环境
  • 谢谢!!我终于解决了。如果有人有同样的麻烦。确保您安装的 React-dom 已更新。在 react-router-dom v6 中,Route 组件不再具有路由道具(历史、位置和匹配),当前的解决方案是使用这些的 React 钩子“版本”在被渲染的组件中使用。但是,React 钩子不能在类组件中使用。所以你需要将你的类转换为函数。并使用useParams()
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 2021-12-25
  • 2021-11-24
  • 2021-10-31
  • 2021-11-07
  • 2022-01-17
  • 2023-03-13
  • 2022-01-01
相关资源
最近更新 更多