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

后端 未结 4 1818
有刺的猬
有刺的猬 2020-12-29 04:31

I decided to learn React and started with the official tutorial. All is good until I get to this state of my code:

var CommentBox = React.createClass({
  ren         


        
相关标签:
4条回答
  • 2020-12-29 04:56

    I am on ES6 and the arrow function did the trick: rawMarkup = () => {}

    0 讨论(0)
  • 2020-12-29 05:04

    Use function declaration ( render() {} or render: function {}) instead of arrow 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

    An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

    0 讨论(0)
  • 2020-12-29 05:04

    A little late post/answer.

    Try to bind your function inside the constructor

    example:

    this.yourfunction = this.yourfunction.bind(this);
    
    0 讨论(0)
  • 2020-12-29 05:09

    I had the same error message:

    Cannot read property 'props' of undefined

    ...but from a different cause: when this is called from within a function, javascript can not reach the variable because this is in an outer scope. (Note: I was in ES5)

    In this case, simply store this in another variable, prior to the function (in the scope of your component): var that = this;

    Then you will be able to call that.props from within the function.

    Hope this helps for other people who had that error message.

    Detailed example below:

    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>
      )
    }

    0 讨论(0)
提交回复
热议问题