2017-04-05 87 views
1

我想呈現一些數據到我的頁面上,但我得到了錯誤「Uncaught TypeError:this.props.getAllContacts不是函數」,似乎無法跟蹤爲什麼。它說錯誤來自這一行:「this.props.getAllContacts();」。我一直在Google上搜索幾個小時。未捕獲TypeError:this.props.getAllContacts不是函數

export default class List extends Component { 
    componentWillMount() { 
    this.props.getAllContacts(); 
    } 

    showContacts(contacts) { 
    return contacts.map((render, index) => { 
     return (
     <ul key={index} className="results-container"> 
      <li>{render.first_name}</li> 
      <li>{render.last_name}</li> 
      <li>{render.email}</li> 
      <li>{render.phone_number}</li> 
      <li>{render.status}</li> 
     </ul> 
    ); 
    }); 
    } 

    render() { 
    const contacts = this.props.getAllContacts; 

    return (
     <div className="list"> 
     <br/> 
     <h1>All Contacts</h1> 
     {this.showContacts(contacts)} 
     </div> 
    ); 
    } 
} 


export default class App extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     contacts: [], 
     result: {}, 
    }; 
    } 

    getAllContacts() { 
    fetch('/contacts') 
    .then(r => r.json()) 
    .then((results) => { 
     this.setState({ 
     contacts: results.data, 
     }); 
     console.log(this.state); 
    }) 
    .catch(err => err); 
    } 

    render() { 
    return (
     <div className="App"> 
     <div className="nav"> 
      <Nav /> 
     </div> 
     <div className="props"> 
      {this.props.children} 
      <List 
      contacts={this.state.contacts} 
      getAllContacts={this.getAllContacts.bind(this)} 
      /> 
     </div> 
     </div> 
    ); 
    } 
} 

任何幫助表示讚賞,謝謝。

+0

'this.props'有兩個屬性('contacts'和'getAllContacts') - 兩個都不是函數。但是'this.props.getAllContacts'的值似乎來自調用'this.getAllContacts()' – James

回答

1

看起來好像你正在使用this.props.getAllContacts作爲一個函數(在componentWillMount中)和聯繫人列表(在渲染)。我想你應該更新列表中的渲染方法,以使用從父組件傳入的聯繫人列表。

render() { 
    const contacts = this.props.contacts; 
    return (
     <div className="list"> 
     <br/> 
     <h1>All Contacts</h1> 
     {this.showContacts(contacts)} 
     </div> 
    ); 
    }