2017-06-12 58 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'。 –

相关问题