1
我建立一個網頁應用程序與反應,我有一個下拉列表頭,它包含鏈接到一個組件,使axios獲取請求,我保存在該狀態的響應,然後我訪問數據像{this.state.authData.authorizationDocumentConfiguration.optionFieldMap.documentTypeOption.label} 它第一次點擊它會拋出這個錯誤Uncaught (in promise) TypeError: Cannot read property 'optionFieldMap' of undefined
但如果雙擊它,它實際上工作並呈現相應的數據。第一次點擊時未定義它的作用| React/Redux/axios
組件:
import React, { Component } from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchUser } from '../../actions';
import PatientCard from './patient_card';
class PatientAdmission extends Component{
constructor(props) {
super(props);
this.state = { authData: [] };
}
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchUser(id);
axios.get("http://ec2-54-221-173-39.compute-1.amazonaws.com:8181/cxf/Demo/demo/get/inpatient-authorization-configuration")
.then(response => this.setState({ authData: response.data }));
}
render(){
const { user } = this.props;
console.log('user this.props response: ',user);
if(!user){
return <div>loading...</div>;
}
return(
<div>
<PatientCard
dob={user.member.dateOfBirth}
/> {this.state.authData.authorizationDocumentConfiguration.optionFieldMap.documentTypeOption.label}
</div>
);
}
}
function mapStateToProps({ users }, ownProps) {
return { user: users[ownProps.match.params.id] };
}
function mapDispatchToProps(dispatch) {
return {
fetchUser: id => fetchUser(id, dispatch)
}
}
export default connect (mapStateToProps, mapDispatchToProps)(PatientAdmission);
是什麼,即時通訊做錯了什麼?
是它的工作!這背後的解釋是什麼? – Emmanuel
您在componentDidMount中發出axois請求,並且由於axios請求花費時間使數據可用並因此使用'{this.state.authData.authorizationDocumentConfiguration && this.state.authData.authorizationDocumentConfiguration.optionFieldMap.documentTypeOption.label}'我們正在檢查'this.state.authData.authorizationDocumentConfiguration'是未定義的。如果它有值,它會傳遞下去,否則傳遞一個空值 –
我明白了,感謝您的快速響應! – Emmanuel