无法访问 属性 对象 React
Can't access property object React
我是 React 的初学者,我遇到了一个我无法解决的问题。
我从 API 调用中得到一个对象。
在我的控制台日志中,它看起来很好。我能够访问一级属性(例如 ID),但是如果我想访问 ACF 值,例如我收到错误:
TypeError: can't access property "date_project", this.state.projet.acf is undefined
我想我没有正确地从 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]
因为异步调用。当它试图访问 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>
)
}
我是 React 的初学者,我遇到了一个我无法解决的问题。 我从 API 调用中得到一个对象。 在我的控制台日志中,它看起来很好。我能够访问一级属性(例如 ID),但是如果我想访问 ACF 值,例如我收到错误:
TypeError: can't access property "date_project", this.state.projet.acf is undefined
我想我没有正确地从 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]
因为异步调用。当它试图访问 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>
)
}