繁体   English   中英

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

[英]setState function undefined in React using ES6 syntax?

我不了解React应用程序中香草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必然。

使用箭头功能时, this仍绑定到您的App类。

但是,当您使用function关键字this绑定到该功能。

根据MDN

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

使用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
   });
});

是指功能。 我建议使用ES6箭头功能:

class App extends Component{
  constructor(props){
    super(props);

    this.state = {videos:[]};

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

这是因为arrow函数没有创建自己的this ,而是使用了封闭执行上下文的this值。 您还可以在变量(或绑定函数)中存储对此的引用:

class App extends Component{
  constructor(props){
    super(props);

    var _this = this;

    this.state = {videos:[]};

    YTSearch({key: API_KEY,term :'surfboards'}, function(videos){
      _this.setState({videos : videos});
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM