Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React JS中获取数据时无法访问类属性_Javascript_Reactjs - Fatal编程技术网

Javascript 在React JS中获取数据时无法访问类属性

Javascript 在React JS中获取数据时无法访问类属性,javascript,reactjs,Javascript,Reactjs,为了获取数据,我创建了一个带有构造函数的类组件 我想将数据放入一个类属性数组中,并在下拉列表中呈现数据 我没有将数据存储为状态,因为项目列表不会更改。但是行,this.myArray=Object.entries=(obj),生成一个 “TypeError:这是未定义的” 错误 如何将返回的数据放置在类属性中 class FilterDropdown extends Component { constructor(props){ super(props)

为了获取数据,我创建了一个带有构造函数的类组件

我想将数据放入一个类属性数组中,并在下拉列表中呈现数据

我没有将数据存储为状态,因为项目列表不会更改。但是行,
this.myArray=Object.entries=(obj),生成一个

“TypeError:这是未定义的” 错误

如何将返回的数据放置在类属性中

class FilterDropdown extends Component {

    constructor(props){
        super(props)    
        this.getFormatItems = this.getFormatItems.bind(this)
        this.myArray = []
        this.getFormatItems()
  }

  getFormatItems() {

      var opts = {
          method: 'GET',      
          headers: {}
      };

      fetch(‘http://example-site.com/api/formats’, opts).then(function (response) {
          return response.json();
      })
      .then(function (obj) {

      // TypeError: this is undefined 
      this.myArray = Object.entries = (obj);

    });
  }  
使用而不是传统的声明,它将自动将函数绑定到类上下文,如下所示

class FilterDropdown extends Component {
    constructor = (props) => {
        super(props)    
        this.getFormatItems = this.getFormatItems.bind(this)
        this.myArray = []
        this.getFormatItems()
    }

    getFormatItems = () => {

      var opts = {
          method: 'GET',      
          headers: {}
      };

      fetch(‘http://example-site.com/api/formats’, opts).then( (response) => {
          return response.json();
      })
      .then((obj) => {

      // TypeError: this is undefined 
      this.myArray = Object.entries = (obj);

    });
}

我认为问题在于
然后
回调函数。使用arrow函数或使用一些以前绑定的函数(如
getFormatItems


您必须在类构造函数中绑定它
this.getFormatItems=this.getFormatItems.bind(this)这一行的目标是什么:
this.myArray=Object.entries=(obj)
?它将一个对象转换为数组。如果我切换到一个箭头函数,我会得到相同的结果。@AlanP对不起,我错过了then函数中的箭头函数,这就是它不起作用的原因
var opts = {
      method: 'GET',      
      headers: {}
  };

  fetch(‘http://example-site.com/api/formats’, opts).then((response) => {
      return response.json();
  })
  .then((obj) => {
  // TypeError: this is undefined 
  this.myArray = Object.entries = (obj);
});