我是 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
最佳答案
YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
this.setState({ videos });
});
抛出错误,因为回调中的 this
并不引用 React 组件的上下文
,而是函数本身的上下文,因此 setState
此处未定义。
在第二个示例中
YTSearch({key: API_KEY, term: 'nba'}, (videos) => {
this.setState({ videos });
});
您正在使用 arrow
函数将该函数绑定(bind)到 react 组件的上下文。另一种方法是使用 bind(this)
YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
this.setState({ videos });
}.bind(this));
关于javascript - ReactJS类型错误: Cannot read property 'setState' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100279/