[英]Unable to access nested attributes on object in React component
我在從React / Redux應用程序中的對象訪問嵌套數據時遇到困難。
特定頁面是“個人資料”頁面,詳細介紹有關患者的信息。
componentDidMount()
生命周期方法用於調用redux操作,該操作將axios.get請求發送到快速后端。 返回JSON對象,並且reducer將此對象轉移到redux狀態。 還原狀態如下(請注意“患者”對象的結構-這是我正在訪問的對象。
Redux
|-- auth
| |-- isAuthenticated
| +-- user
| |-- name
| |-- id
| +-- isAdmin
|-- patients
| |-- patients [ls of 'patient' objects] -> not relevant to this component
| +-- patient
| |-- name
| |-- dateOfBirth
| +-- contact
| |-- phone
| |-- email
| +-- address
+-- errors
在render()
,我將“耐心”對象從redux狀態中拉出:
const { patient } = this.props.patients;
然后在return()
使用“病人”對象。 如果我指的是“頂級”屬性(例如name或dateOfBirth),則可以正常工作。 但是,當我嘗試訪問嵌套屬性(例如電話,電子郵件或地址)時,它失敗並顯示以下錯誤:
TypeError: Cannot read property 'address' of undefined
如果我從下面的代碼中刪除了{patient.contact.address}
,該組件將呈現良好的效果-包括對{patient.name}
和{patient.dateOfBirth}
的引用,將其放回原處,它將失敗。
我也嘗試過將“接觸”物體從道具中拉出,但失敗了。 加載時,所有數據均處於預期的還原狀態-如果我從props中提取控制台后立即console.log(patient)
,瀏覽器控制台將顯示所有數據(無誤)。
為什么我可以獲取患者對象的頂級屬性,但不能獲取嵌套對象的頂級屬性?
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Moment from 'react-moment';
import { getPatientById } from '../../redux/actions/patient.actions';
class PatientDetailed extends Component {
componentDidMount = () => {
if (this.props.match.params.patient_id) {
this.props.getPatientById(this.props.match.params.patient_id);
}
};
render() {
const { patient } = this.props.patients;
return (
<>
<div className="container-fluid">
<div className="card">
<div className="card-body">
<div className="row">
<div className="col-6">
<h6>Name:</h6>
</div>
<div className="col-6">{patient.name}</div>
</div>
<div className="row">
<div className="col-6">
<h6>Date of birth:</h6>
</div>
<div className="col-6">
<Moment format="DD/MM/YYYY">{patient.dateOfBirth}</Moment>
</div>
</div>
<div className="row">
<div className="col-6">
<h6>Address:</h6>
</div>
<div className="col-6">{patient.contact.address}</div>
</div>
</div>
</div>
</div>
</>
);
}
}
PatientDetailed.propTypes = {
getPatientById: PropTypes.func.isRequired,
patients: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
patients: state.patients
});
export default connect(
mapStateToProps,
{ getPatientById }
)(PatientDetailed);
由於要在componentDidMount
方法中獲取數據並更新存儲,因此contacts對象可能在首次渲染時不可用,因此會出現錯誤。 使用前請檢查是否存在
<div className="col-6">{patient.contact && patient.contact.address}</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.