React - this.props looks undefined

I am using a React tutorial. Here's a code that doesn't work when I add a property to a Greeter object

let Greeter=React.createClass({
    render: ()=>{
      let name=this.props.name;
      return (<div>
      <h1>Hello {name}!</h1>
    </div>);
  }
});



ReactDOM.render(
  <Greeter name ="Your name"/>,
  document.getElementById("app")
);

It doesn't work at all when I use Firefox, here is what I get:

unreachable code after returning statementbrowser.min.js: 37: 6409 TypeError: undefined has no properties

+4
source share
2 answers

The reason this doesn't work is because you use the arrow function inside the ES5 component. thisthen undefined due to arrow function, per MDN documentation for arrow functions :

, this, , new.target. ( )

React -, 'autobinding', this . , (- , , , this). , this , undefined render. , undefined .

React:

render: function() {
    //...
}

autobind this , , . ES6, ES6:

render() {
    //...
}

ES6 , . , this , undefined, .

+6

, fat arrow. , , this , . , .

, , ( ).

// _this will be window in regular mode and undefined in strict mode
let _this = this;
let Greeter = React.createClass({
    render: function() {
      let name = _this.props.name;
      return (
         <div>
            <h1>Hello {name}!</h1>
         </div>
      );
  }
});



ReactDOM.render(
  <Greeter name ="Your name"/>,
  document.getElementById("app")
);

, , React component.render(), this component

0

Source: https://habr.com/ru/post/1660000/


All Articles