React教程:TypeError:无法读取属性'道具'的未定义

React Tutorial: TypeError: Cannot read property 'props' of undefined

本文关键字:未定义 道具 读取 TypeError 教程 React 属性      更新时间:2023-09-26

我决定学习React,并从官方教程开始。一切都很好,直到我的代码达到这种状态:

var CommentBox = React.createClass({
  render: () => {
    return (
      <div className="commentBox">
        <h1> Comments </h1>
        <CommentList />
        <CommentForm />
      </div>
    );
  }
});
var CommentForm = React.createClass({
  render: () => {
    return (
      <div className="commentForm">
        Hello, world! I am a comment form;
      </div>
    );
  }
});
var Comment = React.createClass({
  rawMarkup: () => {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return {__html: rawMarkup};
  },
  render: () => {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2> // <--- [[[[[[ ERROR IS HERE ]]]]]]
        <span dangerouslySetInnerHtml={this.rawMarkup} />
      </div>
    );
  }
});
var CommentList = React.createClass({
  render: () => {
    return (
      <div className="commentList">
        <Comment author="Pete Hunt">This is one comment</Comment>
        <Comment author="Jordan Walke">This is *another* comment yo</Comment>
      </div>
    );
  }
});
ReactDOM.render(
  <CommentBox />,
  document.getElementById('content')
);

当我尝试运行它时,我在devtools中得到以下错误:

TypeError:无法读取未定义的属性"props"

并且调试器在标记的行处暂停(参见代码)。当我将鼠标悬停在{this.props.author}中的this上时,我会预览具有props属性的对象和所有内容。。。

使用函数声明(render() {}render: function {})而不是箭头函数render: () => {}

var Comment = React.createClass({
  rawMarkup() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return {__html: rawMarkup};
  },
  render() {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        <span dangerouslySetInnerHtml={this.rawMarkup} />
      </div>
    );
  }
});

Example

与函数表达式相比,arrow function表达式的语法更短,并且在词汇上绑定this值(不绑定自己的this、arguments、super或new.target)。箭头函数总是匿名的。

我收到了相同的错误消息:

无法读取未定义的属性"props"

但原因不同:当从函数内部调用this时,javascript无法访问变量,因为this位于外部范围内(注:我在ES5)

在这种情况下,只需将this存储在函数之前的另一个变量中(在组件范围内):var that = this;

然后,您将能够从函数中调用that.props

希望这对其他收到错误信息的人有所帮助。

下面的详细示例:

render: function() {
  var steps = [];
  var that = this;  // store the reference for later use
  var count = 0;
  this.props.steps.forEach(function(step) {
      steps.push(<Step myFunction={function(){that.props.anotherFunction(count)}}/>);  // here you are
      count += 1;
  });
  return (
    <div>{steps}</div>
  )
}

发布/回答有点晚。

尝试将您的函数绑定到构造函数中

示例:

this.yourfunction = this.yourfunction.bind(this);

我在ES6上,箭头函数完成了任务:rawMarkup=()=>{}