我创建了一个带有构造函数的类组件来获取数据。
我想将数据放入类属性数组中,并将数据呈现在下拉列表中。
我不会将数据存储为状态,因为项目列表不会更改。但是,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/