2

Below method works fine

var DBBox = React.createClass({
  loadArticlesFromServer: function() {
  $.ajax({
    url: this.props.url,
    dataType: 'json',
    data: {username:data.username,isPublished:data.isPublished, heading:data.heading},
    cache: false,
    success: function(data) {
      this.setState({data: data});
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(this.props.url, status, err.toString());
    }.bind(this)
  });
},

But if I change method declaration to arrow function on line 2 like this

loadArticlesFromServer: ()=> {  //error - Cannot read property 'props' of undefined at line 6

or

loadArticlesFromServer= ()=> {  //Syntax error

Am I using arrow function incorrectly or missing something? or is it not supported? I am using chrome and tried enabling harmony flag without any luck.

G.D
  • 305
  • 5
  • 18
  • 3
    You should study the behaviors of the `this` in the arrow functions. You can't use `bind` with arrows. – Redu Oct 09 '16 at 09:14
  • 1
    See [this question](http://stackoverflow.com/questions/31647507/this-values-for-arrow-functions) (no pun intended) – qxz Oct 09 '16 at 09:30
  • Thanks @Redu , pointed me to the right direction. – G.D Oct 09 '16 at 09:42

1 Answers1

0

arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods.

'use strict';
var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b(); // prints undefined, Window
obj.c(); // prints 10, Object {...}
G.D
  • 305
  • 5
  • 18