React - 如何从数组 json 对象的数组中访问单个值

时间:2021-05-25 12:37:39

标签: arrays json reactjs api

我在 localstorage 中有一个 JSON,我想从中访问一些值。

我收到了正确的电子邮件,但是当我尝试获取“company_name”时,它说

类型错误:无法读取未定义的属性“公司”

也请帮我处理role_name

谢谢

Profile.js

import React, { Component } from 'react';
import axios from 'axios';

class Profile extends Component {

  constructor(props) {
    super(props);

    this.state = {
      getUserData:[],
    };
  }   

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  componentDidMount() {
    let getUserData = localStorage.getItem("userData"); 
    this.setState({ 
      getUserData: JSON.parse(getUserData), 
    });   
  }

  render() {
      return (
        <div>             
           <h3>Hello {this.state.getUserData.email}</h3>
            
           <h6>Company Name</h6>
                        
           <h5>{this.state.getUserData.user_profile.company.company_name}</h5>
                        
           <h6>Miles</h6>
                        
           <h5>{I want miles here}</h5>
                        
           <h6>Role Name</h6>
                       
           <h5>{I want role_name here}</h5>
        </div>
      )    
  }
}

export default Profile;

我的 JSON 是这样的-

{"id":6,"email":"rudresh64434@amazon.in","phone":"","is_active":1,"is_verified":1,"is_deleted":0,"qb_id":null,"qb_password":null,"token":"eyJ0eXAiOiJKV1Qi","common_chat_supervisor_id":"60a7a109ce5b15001ecf6e28","user_profile":{"id":6,"user_id":6,"company_id":2,"first_name":"","last_name":null,"profile_photo":null,"gender":null,"date_of_join":null,"date_of_birth":null,"user_roles":[{"id":6,"role_id":7,"user_profile_id":6,"role_name":"company_employee","role_display_name":"Company Employee"}],"company":{"id":2,"company_name":"AMAZON INDIA","company_type":2,"con_name":"ANKIT BOKARE","con_email":"ankitb.verve@gmail.com","company_address1":"Brigade Gateway, 8th floor, 26/1","company_address2":"Dr. Rajkumar Road, Malleshwaram(W)","company_city":"Bangalore","company_state":"Karnataka","company_country":"INDIA","company_zipcode":"560055"},"locations":{"id":5,"user_profile_id":6,"city_id":1,"miles":"1","region":"1","site":"Gujrat"}}}

1 个答案:

答案 0 :(得分:1)

首先,如果您在本地存储中的 userData 是对象,那么您可以将 getUserData 初始化为空白对象,如下所示:-

  constructor(props) {
    super(props);

    this.state = {
      getUserData: {},
    };
  } 

现在当您的组件第一次挂载时,getUserData 将是空白对象,因此当它尝试从空白对象访问 user_profile 时,它将返回 undefined。

要解决此问题,您可以使用 optional chaining 如下所示:-

<h5>{this.state.getUserData?.user_profile?.company?.company_name}</h5>