2017-08-16 89 views
1

我不明白在一个React应用程序中的香草JavaScript和ES6之间的语法差异。 我不工作的第一代码是setState函数在使用ES6语法的React中未定义?

class App extends Component{ 
constructor(props){ 
super(props); 

this.state = {videos:[]}; 

YTSearch({key: API_KEY,term :'surfboards'},function(videos){ 
    this.setState({videos : videos}); 
}); 
} 

这给在控制台

错误“未定义的‘一’不能读取属性”的setState但改变语法

YTSearch({key: API_KEY,term :'surfboards'},(videos)=>{ 
    this.setState({videos : videos}); 
}); 

解决了这个问题。是不是都一样的东西(我可能是错的)。采用

function(videos){} 

(videos) => {} 

我不舒服的javascript,所以任何帮助表示赞赏。

+3

的可能的复制[Arrow功能VS函数声明/表情:他们当量/更换?](https://开头计算器。 com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – 4castle

回答

4

这是由于this被绑定。

当使用箭头功能this仍然绑定到您的App类。

但是,当您使用function关键字this绑定到该函数。

按MDN

直到箭头的功能,每一个新的功能定义自己的这个值。

使用function关键字可以采取两种方法。

首先,

YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
    this.setState({ 
     videos : videos 
    }); 
}.bind(this)); 

,否则你可以这样做:

//assign this to new variable that to use when setting state 
let that = this; 

YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
    that.setState({ 
     videos : videos 
    }); 
}); 
+0

如果你不介意你能否展示我将如何使用函数关键字编写上述代码。 – Buttersnips

+0

@Buttersnips看到更新的答案,这是你想要的吗? –

+0

是的。帮助我。 – Buttersnips

2

指的是工作。 我建议使用ES6箭头功能:

class App extends Component{ 
    constructor(props){ 
    super(props); 

    this.state = {videos:[]}; 

    YTSearch({key: API_KEY,term :'surfboards'}, (videos) => { 
     this.setState({videos : videos}); 
    }); 
    } 
} 

这是因为箭头功能不会创建自己的,在封闭执行上下文的这个值被使用。 您还可以存储在变量(或绑定功能)参考这个

class App extends Component{ 
    constructor(props){ 
    super(props); 

    var _this = this; 

    this.state = {videos:[]}; 

    YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
     _this.setState({videos : videos}); 
    }); 
    } 
} 
相关问题