Reactjs 如何将mobx反应写入成功的数据获取?
我需要进行两次连续的数据提取。我需要获取包含数据源列表的设备,然后在UI中活动的设备上获取数据源的内容。我知道我需要某种反应,但我不知道该怎么做。现在我有: 设备UI组件片段 MobX商店Reactjs 如何将mobx反应写入成功的数据获取?,reactjs,mobx,Reactjs,Mobx,我需要进行两次连续的数据提取。我需要获取包含数据源列表的设备,然后在UI中活动的设备上获取数据源的内容。我知道我需要某种反应,但我不知道该怎么做。现在我有: 设备UI组件片段 MobX商店 我知道我需要对isLoadingDevices为false做出反应,并且我需要在该反应发生时使用正确的deviceName启动setActiveDevice,但我不知道该如何做。如果我理解正确,当可观察的isLoadingDevices为false时,您希望调用setActiveDevice。 如您所述,您可
我知道我需要对isLoadingDevices为false做出反应,并且我需要在该反应发生时使用正确的deviceName启动setActiveDevice,但我不知道该如何做。如果我理解正确,当可观察的
isLoadingDevices
为false时,您希望调用setActiveDevice
。
如您所述,您可以使用reaction,只需从“mobx”导入它,并在构造函数中使用它:
constructor() {
reaction(
// The callback will run only on change
// of observables described in this function
() => this.isLoadingDevices,
// The callback, to be called each time the above expression changes
() => {
if (!this.isLoadingDevices) {
this.setActiveDevice(/* Params */)
}
}
)
}
请注意,您可能可以根据加载的数据将
activeDevice
表示为计算值?
class DeviceStore {
userStore
transportLayer
@observable devices = []
@observable isLoadingDevices = true
@observable activeDevice = null
constructor(transportLayer, userStore) {
this.transportLayer = transportLayer
this.userStore = userStore
this.loadDevices()
}
loadDevices() {
this.isLoadingDevices = true
this.transportLayer.fetchDevices(this.userStore.username)
.then(devices => {
devices.forEach(json => this.updateDeviceFromServer(json))
this.isLoadingDevices = false
})
}
loadFeeds(deviceName) {
let device =
this.devices.find(device => device.name === deviceName)
this.transportLayer.fetchFeeds(this.userStore.username, device)
.then(feeds => {
console.log(feeds)
this.updateDeviceFromServer({
name: deviceName,
feeds: feeds
})
})
}
updateDeviceFromServer(json) {
let device =
this.devices.find(device => device.name === json.name)
if (!device) {
device = new Device(this, json)
this.devices.push(device)
} else {
device.updateFromJson(json)
}
}
setActiveDevice(deviceName) {
this.activeDevice = deviceName
this.loadFeeds(deviceName)
}
}
constructor() {
reaction(
// The callback will run only on change
// of observables described in this function
() => this.isLoadingDevices,
// The callback, to be called each time the above expression changes
() => {
if (!this.isLoadingDevices) {
this.setActiveDevice(/* Params */)
}
}
)
}