如何编写 mobx 对成功获取数据的反应?

How to write mobx reaction to successful data fetch?

我需要连续两次获取数据。我需要获取包含数据源列表的设备,然后我需要获取 UI 中处于活动状态的设备上的数据源内容。我发现我需要以某种方式做出反应,但我不确定如何去做。现在我有:

设备 UI 组件片段

componentDidMount() {
    DeviceStore.setActiveDevice(this.props.routeParams.deviceName)
}

MobX 商店

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

我知道我需要对 isLoadingDevices 为假做出反应,并且我需要在该反应发生时使用正确的设备名称启动 setActiveDevice,但我不确定该怎么做。

如果我没理解错的话,您想在可观察的 isLoadingDevices 为假时调用 setActiveDevice。 您可以使用反应,如您所说,只需从 '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 */)
            }
        }
    )
}