【发布时间】:2016-05-23 06:38:49
【问题描述】:
我刚从 ES5 的背景开始学习 ES6 和 ReactJS。
这段 ES6 代码让我摸不着头脑。
代码#1:
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [] };
YTSearch({key: API_KEY, term: 'surfboard'}, function(data) {
this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
});
}
render() {
return (
<div>
<SearchBar />
</div>
);
}
}
我在this.setState 中得到一个error
bundle.js:19826 TypeError: Cannot read property 'setState' of undefined(…)
但是,如果我这样做了
代码#2:
YTSearch({key: API_KEY, term: 'surfboard'}, (data) => {
this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
});
这很好用。
我可以理解在第一种情况下,一般function 中的this 的范围在回调(如AJAX)中是不同的。但在示例 #2 中,情况有何变化?
【问题讨论】:
-
谢谢你我的坏。打扰一下。我刚开始用 reactJS / ES6 编码。只是想习惯新的语法。你们摇滚!
标签: javascript reactjs ecmascript-6