javascript - 无法访问属性对象 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]
解决方案
这是因为异步调用。当它试图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-native - how can i change the options of my drawerNavigator with React Native when user is logged
- angular - Angular Clear Cache On update
- bash - bash:管道空输入的默认输出
- ios - Failure to determine screen point of hittable tableViewCell
- r - 栅格计算操作中的纬度
- windows - How to check if a folder path matches USERs folder in BAT script
- html - 单击时如何删除输入字段的边框(焦点指示)
- javascript - Action for clicked marker on Google Map
- lodash - Rollupjs:忽略代码行
- tensorflow - Tensorflow 代码准确率没有提高