第一次点击未定义,第二次点击它有效 | React/Redux/axios

Undefined on the first click in the second one it works | React/Redux/axios

我正在构建一个带有 React 的 Web 应用程序,我有一个 Header 和一个下拉菜单,它包含 Link 到一个组件,该组件发出 axios get 请求,我将响应保存在状态中,然后我访问像 {this.state.authData.authorizationDocumentConfiguration.optionFieldMap.documentTypeOption.label} 这样的数据 第一次点击它会抛出这个错误 Uncaught (in promise) TypeError: Cannot read property 'optionFieldMap' of undefined 但如果双击它,它实际上可以工作并呈现相应的数据。

组件:

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);

我做错了什么?

发生这种情况是因为您正在从 axios 调用中获取 authData,并且在 axios 请求完成之前它将不可用

试试这个

return(
      <div>
        <PatientCard
          dob={user.member.dateOfBirth}
        />        {this.state.authData.authorizationDocumentConfiguration && this.state.authData.authorizationDocumentConfiguration.optionFieldMap.documentTypeOption.label}                        
      </div>
    );