首页 > 解决方案 > 无法访问属性对象 React

问题描述

我是 React 的初学者,我面临着一个我无法解决的问题。我从 API 调用中得到一个对象。在我的控制台日志中,它看起来不错。我可以访问一级属性(例如 ID),但是如果我想访问 ACF 值,例如,我会收到错误消息:

TypeError:无法访问属性“date_project”,this.state.projet.acf 未定义

我想我没有正确地从 ACF 对象获取数据,但我不明白该怎么做。

这是我的代码:

[import React, { Component } from 'react';
import '../App.scss';
import {Row, Container, Col} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Config} from '../config';
import { withRouter } from "react-router";

class Projet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      projet: \[\]
    };
 }

 async componentDidMount() {
  const id = parseInt(this.props.match.params.id);
  const response = await fetch(Config.apiUrl + `wp-json/wp/v2/projet/${id}`);
  const json = await response.json();
  this.setState({ projet: json });
}

renderProjet() {
  console.log('projet', this.state.projet)
  return (
    <p>{this.state.projet.acf.date_projet}</p>
  )
}

  render() {
    return (
      <Container fluid className="App-home">
        <Row className="align-items-left">
          <div>
            { this.renderProjet()}
          </div>
        </Row>
       </Container>
    )
  }
}

export default (Projet);][1]

错误 目的

标签: javascriptreactjsobjectrendering

解决方案


这是因为异步调用。当它试图acf在那个时候访问它时它不可用。如果数据不可用,要么创建加载变量来跟踪它,要么不渲染组件:

render() {
    if(!this.state.projet?.acf) return null; //Do not render if data is not available
    return (
      <Container fluid className="App-home">
        <Row className="align-items-left">
          <div>
            { this.renderProjet()}
          </div>
        </Row>
       </Container>
    )
  }


推荐阅读