2017-07-31 106 views
1

屬性映射我很新的反應,我想在數據把從鐵軌API,但我得到的錯誤TypeError: Cannot read property 'map' of undefined陣營無法讀取的不確定

如果我使用的反應開發工具,我可以看到狀態,我可以,如果我惹在控制檯與它周圍使用$r.state.contacts有人能與我有什麼做錯了幫助看見的聯絡?我的組件看起來是這樣的:

import React from 'react'; 
import Contact from './Contact'; 

class ContactsList extends React.Component { 
    constructor(props) { 
    super(props) 
    this.state = {} 
    } 

    componentDidMount() { 
    return fetch('http://localhost:3000/contacts') 
     .then(response => response.json()) 
     .then(response => { 
     this.setState({ 
      contacts: response.contacts 
     }) 
     }) 
     .catch(error => { 
     console.error(error) 
     }) 
    } 

    render(){ 
    return(
    <ul> 
     {this.state.contacts.map(contact => { return <Contact contact{contact} />})} 
     </ul> 
    ) 
    } 
} 

export default ContactsList; 
+0

你確定'response.contacts'是一個數組嗎? – PeterMader

回答

3

您需要定義的contacts內部構造函數的默認值,因爲componentDidMount將初始渲染後,並在第一渲染this.state.contacts得到所謂將不確定。這就是爲什麼你所得到的錯誤:

Cannot read property 'map' of undefined

要麼定義內部構造的contacts

constructor(props) { 
    super(props) 
    this.state = { 
     contacts: [] 
    } 
} 

或使用其地圖前,把檢查:

{this.state.contacts && this.state.contacts.map(....) 

注:您需要分配唯一的關鍵地圖裏面的每個元素,檢查DOC

+0

Doh!感謝現在的工作就像一個魅力,當12mins均達到我將標誌着這個作爲答案。 – Ollie2619

+0

高興,它解決您的問題:) –