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



我在本地存储中有一个JSON,我想访问其中的一些值。

我收到了正确的电子邮件,但当我试图获得"company_name"时,它会显示

类型错误:无法读取未定义的的属性"company">

也请帮助我使用角色名称

谢谢

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是对象,则可以将getUserData初始化为空白对象,如下所示:-

constructor(props) {
super(props);
this.state = {
getUserData: {},
};
} 

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

为了解决这个问题,你可以使用如下可选的链接:-

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

最新更新