本文介绍了ReactJS TypeError:无法读取属性'setState'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ReactJS中是新的,我遇到一些问题。



我还了解了 ES6 语法,并表示以下代码的意思相同。



1。

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

2。

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

但是,第一种方式抛出了这个错误

  TypeError:无法读取未定义的属性'setState'


解决方案
  YTSearch({key:API_KEY,term:'nba'},function(videos){
this.setState({videos}) ;
});

抛出一个错误,因为这里这个回调不是指React Component 的上下文,而是函数本身的上下文,因此 setState 在此未定义。



在第二个例子中

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

您正在使用 arrow 函数将函数绑定到反应组件的上下文。另一种做同样的方法是使用 bind(this)

  YTSearch({key:API_KEY,term:'nba'},function(videos){
this.setState({videos});
} .bind(this));


I am new at ReactJS, and I encounter some problems.

I also learned about the ES6 syntax, and it said the following codes are the same meaning.

1.

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

2.

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

However, the first way threw this error

TypeError: Cannot read property 'setState' of undefined
解决方案
YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
});

Throws an error because here this inside the callback doesn't refer to the context of React Component rather the context of the function itself and hence setState is undefined here.

In the second example

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

You are making use of arrow function to bind the function to the context of the react component. Another way to do the same would be to use bind(this)

YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
}.bind(this));

这篇关于ReactJS TypeError:无法读取属性'setState'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:34