2017-06-12 113 views
0

我目前正在觀看React Path @ PluralSight(這是很棒的方式),我正在經歷兩個組件的一些問題。爲什麼我的組件不能渲染?

我有這個組件稱爲作者,這是在這裏:

class Authors extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      authors: [] 
     }; 
    } 
    componentDidMount() { 
     if (this.isMounted()){ 
      this.setState({ authors: AuthorApi.getAllAuthors() }); 
     } 
    } 
    render() { 
     return(
      <div className="container"> 
       <h1>Authors</h1> 
       <hr /> 
       <AuthorList authors={this.state.authors} /> 
      </div> 
     ); 
    } 
} 

和組件AuthorList,這是在這裏:

const AuthorList = (props) => { 
    const createAuthorRow = (author) => { 
     return(
      <tr key={author.id}> 
       <td><a href={"/#authors/" + author.id}>{author.id}</a></td> 
       <td>{author.firstName} {author.lastName}</td> 
      </tr> 
     ); 
    }; 
    return( 
     <div> 
      <table className="table"> 
       <thead> 
        <th>id</th> 
        <th>Name</th> 
       </thead> 
       <tbody> 
        {this.props.authors.map(createAuthorRow, this)} 
       </tbody> 
      </table> 
     </div> 
    ); 
}; 

的問題是,他們沒有渲染!他們都在同一個文件中,不知何故,他們不會呈現。我曾嘗試爲每個文件製作單獨的文件,但它們仍不會呈現。我錯過了什麼嗎?

+0

在chrome中打開您的控制檯開發人員工具,並告訴我們到底發生了什麼錯誤? – Fiido93

+0

TypeError:「this.isMounted」不是函數 –

回答

1

您是否在控制檯中收到任何運行時異常?正如你的問題所寫 - 你應該 - 這就是爲什麼你沒有看到任何渲染。

AuthorList這裏實現的是一個無狀態的功能組件。您在組件this中引用了this,其中功能組件引用了該功能,而不是React類,它將定義關閉propsthis - 將道具作爲參數傳入 - 您可以直接引用它。

因此改變

<tbody> 
    {this.props.authors.map(createAuthorRow, this)} 
</tbody> 

<tbody> 
    {props.authors.map(createAuthorRow)} 
</tbody> 

而且 - 請查看this article on the React team deprecating isMounted 正如你指出的 - 這是不是一個功能 - 連同上面的建議 - 將其刪除。您已經在使用componentDidMount生命週期方法 - 在調用這個函數的時候,從您的後端獲取結果對於您正在使用的示例是正確的。

+0

是的,我說,this.isMounted()不是一個函數 –

+0

@RenéVidrialesTrujillo - 我更新了答案,以解決您使用isMounted '以及。 – syllabix

+0

謝謝!我遵循你的建議:擺脫'this.isMounted()',現在一切正常。另外,我擺脫了無狀態組件中的'this'。 –

相關問題