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

标签 javascript reactjs

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

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

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

“TypeError: this is undefined” error.

如何将返回的数据放入类属性中?

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);

    });
  }  

最佳答案

我认为问题出在then回调函数上。使用箭头函数或使用一些先前绑定(bind)的函数(例如 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);
});

关于javascript - 在 React JS 中获取数据时无法访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482745/

相关文章:

JavaScript 换行问题

javascript - Div 中的文本卡在右侧

javascript - React/Mobx - 组件正在重新渲染,但未调用 componentWillReceiveProps()

javascript - JS单页应用程序和基于PHP的登录系统?

javascript - 使 RBSheet 可作为 React-Native 小部件重复使用

javascript - 如何使用react.js处理单选按钮

javascript - 以正确的顺序执行 javascript Ajax 和非 ajax 调用

javascript - 如何使用 ReactJS 更新内容

javascript - onClick 能够填充模式并提交表单

javascript - 使用钩子(Hook)检测 React 组件外部的点击