簡體   English   中英

React教程:TypeError:無法讀取未定義的屬性“ props”

[英]React Tutorial: TypeError: Cannot read property 'props' of undefined

我決定學習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{this.props.author} ,我得到它具有對象的預覽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,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 =()=> {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM