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