【发布时间】:2019-12-05 14:29:41
【问题描述】:
我正在尝试使用 setState 函数在此回调函数中将我的“绘图”状态设置为 json 对象“数据”。我知道“数据”对象已正确传递,因为我能够在 this.setState() 调用之前将其记录到控制台中,但是,当我尝试设置状态时,我收到“TypeError:不能读取未定义的属性‘setState’。” 代码如下:
constructor(props) {
super(props);
this.state = {
plot: null,
};
this.getPlot = this.getPlot.bind(this);
this.getPlot.fetchServiceData = fetchServiceData.bind(this);
}
getPlot() {
fetchServiceData('/plot', function (data) {
this.setState({plot: data}, function () {
if(this.state.plot) {
Bokeh.embed.embed_item(this.state.plot, 'AAPL_plot');
}else{
console.error('Unable to set plot state.')
}
});
});
}
componentDidMount() {
this.getPlot();
}
这是我的 fetchServiceData 函数,在另一个导入的文件中:
function fetchServiceData(apiPath, callback) {
let data = null;
fetch(BASE_SERVICE_URL + apiPath)
.then(response => response.json())
.then(function(data) {
console.log(this)
callback(data);
})
.catch(error => console.log(error));
}
export { fetchServiceData };
我是否需要以某种方式将“this”绑定到我的 fetchServiceData() 函数或该函数的回调?
【问题讨论】:
标签: reactjs components state