我不明白 React 应用程序中 vanilla javascript 和 ES6 之间的语法差异。 我的第一个不起作用的代码是
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 不太满意,所以非常感谢您的帮助。
最佳答案
这是由于 this
的绑定(bind)方式所致。
当使用箭头函数时,this
仍然绑定(bind)到您的 App
类。
但是,当您使用 function
关键字时,this
会绑定(bind)到该函数。
根据 MDN
Until arrow functions, every new function defined its own this value.
使用 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
});
});
关于javascript - 使用 ES6 语法在 React 中未定义 setState 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45722561/