小编典典

ReactJS TypeError:无法读取属性“ setState”

reactjs

我是ReactJS的新手,遇到一些问题。

我还了解了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

阅读 247

收藏
2020-07-22

共1个答案

小编典典

YTSearch({key: API_KEY, term: ‘nba’}, function(videos) {
this.setState({ videos });
});

引发错误,因为在this此回调内部并未引用context of React Component函数本身的上下文,因此setState此处未定义。

在第二个例子中

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

您正在使用arrow函数将函数绑定到react组件的上下文。另一种方法是使用bind(this)

YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
}.bind(this));
2020-07-22