簡體   English   中英

React - 如何從數組 json object 訪問單個值

[英]React - How to access single value from array of array json object

我在本地存儲中有一個 JSON ,我想從中訪問一些值。

我得到了正確的 email,但是當我試圖獲得“公司名稱”時,它說

TypeError:無法讀取未定義的屬性“公司”

請也幫助我處理角色名稱

謝謝

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"}}}

首先,如果您在本地存儲中的userData是 object ,那么您可以將getUserData初始化為空白 object ,如下所示:-

  constructor(props) {
    super(props);

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

現在,當您的組件第一次安裝時, getUserData將為空白 object 因此當它嘗試從空白 object 訪問user_profile時,它將返回未定義。

要解決此問題,您可以使用如下的可選鏈接:-

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM