【问题标题】:Arrow functions not working in browser箭头功能在浏览器中不起作用
【发布时间】:2016-10-09 09:04:17
【问题描述】:

下面的方法很好用

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

但是如果我像这样在第 2 行将方法声明更改为箭头函数

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

loadArticlesFromServer= ()=> {  //Syntax error

我是否错误地使用了箭头功能或遗漏了什么?还是不支持?我正在使用 chrome 并尝试启用和谐标志,但没有任何运气。

【问题讨论】:

  • 您应该研究箭头函数中this 的行为。您不能将bind 与箭头一起使用。
  • this question(没有双关语)
  • 感谢@Redu,为我指明了正确的方向。

标签: javascript node.js reactjs ecmascript-6


【解决方案1】:

箭头函数表达式最适合非方法函数。让我们看看当我们尝试将它们用作方法时会发生什么。

'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 {...}

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2018-01-27
    相关资源
    最近更新 更多