[英]displaying nested JSON with react js
我有一個像這樣的對象:
export const contact = {
_id: "1",
first:"John",
name: {
first:"John",
last:"Doe"
},
phone:"555",
email:"john@gmail.com"
};
我正在讀它
return (
<div>
<h1>List of Contact</h1>
<h1>{this.props.contact._id}</h1>
</div>
)
在這種情況下,我將獲得預期的輸出。
return (
<div>
<h1>List of Contact</h1>
<h1>{this.props.contact.name.first}</h1>
</div>
)
但是當我閱讀嵌套屬性時,我得到了類似的錯誤
未捕獲的TypeError:無法讀取未定義的屬性“第一個”
如何讀取這些嵌套對象之王的反應? 這是我的資料
您需要在此處解決三件事:
contacts-data
並且我在name
對象中看不到任何first
屬性: export const contacts = {
"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [{
"type": "home",
"number": "111 111-1111"
}, {
"type": "fax",
"number": "222 222-2222"
}]
};
this.props.fetchContacts();
在componentDidMount
,因此在第一個render
調用中, state
仍然為空, action
調用和reducer
將傳遞新的props或更改狀態,然后您進入第二個render
調用,此時您已准備好使用數據。 render() {
const { contacts } = this.props;
return (
<div>
<h1>List of Contacts</h1>
<h2>{contacts && contacts.name && contacts.name.first
//still getting error. "this.props.contacts.name" alone works
}</h2>
<h2>{contacts && contacts.address && contacts.address.city}</h2>
</div>
)
}
this.props.contact.name.first
是錯字嗎? 不應該是contacts
而不是contact
嗎? 編輯 :作為評論的后續內容,作為JavaScript(或該方式的任何其他語言)的一般規則,在嘗試訪問對象的屬性之前,應始終檢查對象的存在引用。
對於您的用例,如果您必須具有要渲染的值,則可以使用defaultProps
,甚至可以簡化數據方案。
這更容易管理:
export const contacts =
{
"fName": "mkyong",
"lName": "lasty",
"age": 30,
"streetAddress": "88 8nd Street",
"city": "New York",
"homeNumber": "111 111-1111",
"faxNumber": "222 222-2222"
};
比這個:
export const contacts =
{"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.