我是ReactJS的新手,遇到一些问题。
我还了解了ES6语法,它说以下代码具有相同的含义。
ES6
1。
YTSearch({key: API_KEY, term: 'nba'}, function(videos) { this.setState({ videos }); });
2。
YTSearch({key: API_KEY, term: 'nba'}, (videos) => { this.setState({ videos }); });
但是,第一种方法引发此错误
TypeError: Cannot read property 'setState' of undefined
YTSearch({key: API_KEY, term: ‘nba’}, function(videos) { this.setState({ videos }); });
引发错误,因为在this此回调内部并未引用context of React Component函数本身的上下文,因此setState此处未定义。
this
context of React Component
setState
在第二个例子中
您正在使用arrow函数将函数绑定到react组件的上下文。另一种方法是使用bind(this)
arrow
bind(this)
YTSearch({key: API_KEY, term: 'nba'}, function(videos) { this.setState({ videos }); }.bind(this));