使用 ES6 语法在 React 中未定义 setState 函数?

But*_*ips 1 javascript ecmascript-6 reactjs

我不明白 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});
});
}
Run Code Online (Sandbox Code Playgroud)

这会在控制台中出现“无法读取未定义属性”的“setState”错误

但将语法更改为

YTSearch({key: API_KEY,term :'surfboards'},(videos)=>{
   this.setState({videos : videos});
});
Run Code Online (Sandbox Code Playgroud)

解决问题。两者不是一回事(我可能错了)。使用

function(videos){}
Run Code Online (Sandbox Code Playgroud)

(videos) => {}
Run Code Online (Sandbox Code Playgroud)

我对 javascript 不满意,因此感谢您的任何帮助。

Pau*_*ald 5

这是由于如何this绑定。

使用箭头函数时this仍然绑定到您的App类。

但是,当您使用function关键字this绑定到该函数时。

根据 MDN

在箭头函数之前,每个新函数都定义了自己的 this 值。

使用function关键字您可以采取两种方法。

首先,

YTSearch({key: API_KEY,term :'surfboards'}, function(videos){
  this.setState({
      videos : videos
   });
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

否则你可以这样做:

//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
   });
});
Run Code Online (Sandbox Code Playgroud)