我刚刚开始使用 mobx 和 React(顺便说一句,这是一个很棒的团队!),我的商店遇到了一些问题。我想从现有 API 中异步获取一些数据,然后使用这些数据来更新我商店中的一些现有可观察对象:
class StationStore {
@observable stations = []
loadStations() {
fetch('http://localhost:3000/api/station/getStations')
.then(function(response) { return response.json() })
.then(stations=>this.parseStations(stations));
}
@action parseStations(stations) {
var newStations = stations.map((station)=>{
let s = new Station;
s.id=station.id;
s.name=station.Text;
s.deviceType=station.DeviceType;
return s;
});
this.stations.replace(newStations);
}
}
如您所见,我需要将逻辑分为两个单独的函数,以便能够访问 this.stations
。我尝试将 map 和替换部分包含到 loadStations()
的第二个 then() 中,但是当我这样做时,我无法访问我的商店,因为这是未定义的。
我该如何解决这个问题?
最佳答案
使用 var self = this;
应该可以解决您的问题
class StationStore {
@observable stations = [];
loadStations() {
var self = this;
fetch('http://localhost:3000/api/station/getStations')
.then(function (response) {
return response.json()
})
.then(stations => {
self.stations.replace(stations.map((station) => {
let s = new Station;
s.id = station.id;
s.name = station.Text;
s.deviceType = station.DeviceType;
return s;
}));
});
}
}
关于javascript - 如何重写这个 promise 链以避免需要多个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415512/