2017-03-23 46 views
0

我剛剛從reactjs開始並做了一個教程。 本教程似乎並未完全更新。 我總是收到此錯誤信息:錯誤:未捕獲TypeError:無法讀取未定義的屬性「地圖」

Uncaught TypeError: Cannot read property 'map' of undefined 
    at ContactsList.render (ContactsList.js:40) 
    at ReactCompositeComponent.js:796 
    at measureLifeCyclePerf (ReactCompositeComponent.js:75) 
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795) 
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822) 
    at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746) 
    at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724) 
    at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645) 
    at ReactCompositeComponentWrapper.receiveComponent (ReactCompositeComponent.js:547) 
    at Object.receiveComponent (ReactReconciler.js:125) 

這是我的代碼:

import React, { Component } from 'react'; 
import Contact from './Contact'; 

class ContactsList extends Component { 

    constructor() { 
     super(); 
     this.state = { 
      search: '' 
     }; 
    } 

    updateSearch(event) { 
     this.setState({ search: event.target.value.substr(0,20) }) 
    } 

    render() { 
     return (

      <div> 
       <ul> 
       { 
        this.props.contacts.map((contact)=> { 
         return <Contact contact={contact} key={contact.id} /> 
        }) 

       } 
       </ul> 
       <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} /> 
      </div> 
     ); 
    } 
} 

export default ContactsList 

ContactList類被稱爲是這樣的:

import React, { Component } from 'react'; 
import ReactDOM, { render } from 'react-dom' 
import ContactsList from './ContactsList'; 

let contacts = [{ 
    id: 3, 
    name: 'Ray', 
    phone: '123 555 5555' 
}, 
{ 
    id: 2, 
    name: 'Jay', 
    phone: '123 123 5555' 
}, 
{ 
    id: 1, 
    name: 'May', 
    phone: '123 123 1234' 
}] 

class App extends Component { 
    render() { 
    console.log('contacts:' + this.props.contacts); 
    return (
     <div> 
     <h1>Contacts List</h1> 
     <ContactsList contacts={this.props.contacts} /> 
     </div> 
    ); 
    } 
} 

export default App; 

ReactDOM.render(<App contacts={contacts} />,document.getElementById('root')); 

我居然不知道,爲什麼會出現這個錯誤。我已經搜索了很多,但沒有任何解決方案。也許有人可以給我一個提示,錯誤原因是什麼以及如何解決它? 在此先感謝。

+1

您如何期待'this.props.contacts'具有價值? – Pointy

+0

沒有聯繫人作爲prop添加到組件。因此不會有它的地圖屬性。 –

+0

好的,但怎麼辦?請參閱我的編輯。對不起,我是'react'中的絕對初學者。 –

回答

1

原因是您從App組件中傳入this.props.contactscontacts不是您的應用程序的屬性,甚至不是狀態,它是範圍中的標準JavaScript變量。

這應該工作。

<ContactsList contacts={ contacts } /> 

顯然,如果你把它狀態App在未來,那麼你會進行相應的調整。

+0

哦,男人。謝謝你的幫助。來自我的愚蠢的錯誤。 :-(我總是在'ContactsList'中搜索一個解決方案/錯誤,因爲名字已經顯示出來了。無論如何,非常感謝! –

+0

我不確定你在我之後添加了'App contacts = {contacts}'回答與否,但是這應該達到與我所建議的相同的效果,也就是說,這會將'contacts'作爲一個屬性提供給App,這將使'App'呈現可以執行'this.props.contacts'。 – dpwrussell

相關問題