簡體   English   中英

用react js顯示嵌套的JSON

[英]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:無法讀取未定義的屬性“第一個”

如何讀取這些嵌套對象之王的反應? 這是我的資料

您需要在此處解決三件事:

  1. 這是您的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"
  }]
};
  1. 您正在調用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>
    )
  } 
  1. 您正在嘗試使用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.

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