Reactjs Can';在React容器组件中找不到内部方法

Reactjs Can';在React容器组件中找不到内部方法,reactjs,Reactjs,我试图将AJAX检索到的数据放入父React组件,以便将其反馈给子组件。我使用流行的模式来定义,其中使用注释列表作为示例: 组件/CommentList.js import React from 'React'; export class CommentList extends React.Component { constructor(props) { super(props); } render() { return <ul> {this.props

我试图将AJAX检索到的数据放入父React组件,以便将其反馈给子组件。我使用流行的模式来定义,其中使用注释列表作为示例:

组件/CommentList.js

import React from 'React';

export class CommentList extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <ul> {this.props.comments.map(renderComment)} </ul>;
  }
  renderComment({body, author}) {
    return <li>{body}—{author}</li>;
  }
}
从“React”导入React;
导出类CommentList扩展React.Component{
建造师(道具){
超级(道具);
}
render(){
返回
    {this.props.comments.map(renderComment)}
; } renderComment({body,author}){ 返回
  • {body}-{author}
  • ; } }
    components/CommentListContainer.js

    import React from 'React';
    import { CommentList } from './CommentList';
    
    
    export class CommentListContainer extends React.Component {
      constructor() {
        super();
        this.state = { comments: [] }
      }
    
      componentDidMount() {
        $.ajax({
          url: "http://get/some/api",
          dataType: 'json',
          success: function(comments) {
            this.setState({comments: comments});
          }.bind(this)
        });
      }
      render() {
        return <CommentList comments={this.state.comments} />;
      }
    }
    
    从“React”导入React;
    从“/CommentList”导入{CommentList};
    导出类CommentListContainer扩展React.Component{
    构造函数(){
    超级();
    this.state={comments:[]}
    }
    componentDidMount(){
    $.ajax({
    url:“http://get/some/api",
    数据类型:“json”,
    成功:功能(评论){
    this.setState({comments:comments});
    }.绑定(此)
    });
    }
    render(){
    回来
    }
    }
    
    index.js:Web包的入口点

    import React from 'react'
    import { render } from 'react-dom'
    import { CommentListContainer } from './components/CommentListContainer';
    
    window.React = React;
    
    render(
      <CommentListContainer />,
      document.getElementById('nav__react-target')
    )
    
    从“React”导入React
    从'react dom'导入{render}
    从“./components/CommentListContainer”导入{CommentListContainer};
    window.React=反应;
    渲染(
    ,
    document.getElementById('nav\uu react-target')
    )
    
    执行所有这些操作时,我会出现以下错误:

    未捕获引用错误:未定义renderComment

    我移动了这些方法,并在不同的位置调整了依赖项的导入,但运气不好。有什么想法吗


    提前感谢。

    您没有对ES2015类的同级方法的无保护引用(就像您在Java/C#等中所做的那样)-相反,您需要显式引用
    ,以获得类的方法:

    render() {
      // I changed map(renderComment) to map(this.renderComment)
      return <ul>{this.props.comments.map(this.renderComment)}</ul>;
    }
    
    render(){
    //我将map(renderComment)更改为map(this.renderComment)
    返回
      {this.props.comments.map(this.renderComment)}
    ; }
    Sean Viera:这很有道理……这让事情运转起来。谢谢