MobX

MobX

  • API 参考
  • English Doc
  • 赞助商
  • GitHub

›Tips & Tricks

Introduction

  • 关于 MobX
  • 关于本文档
  • 安装
  • MobX 主旨

MobX core

  • Observable state
  • Actions
  • Computeds
  • Reactions {🚀}

MobX and React

  • 集成React(react-integration)
  • React 优化 {🚀}

Tips & Tricks

  • 定义数据存储
  • 理解响应性
  • 使用子类
  • 分析响应性 {🚀}
  • 含参数的计算值 {🚀}
  • MobX-utils {🚀}
  • 自定义 observables {🚀}
  • 惰性 observables {🚀}
  • 集合工具 {🚀}
  • 拦截与观察 {🚀}

Fine-tuning

  • 配置 {🚀}
  • 启用装饰器语法 {🚀}
  • 从MobX 4/5迁移 {🚀}

Others

  • 链接
Edit

创建惰性 observables {🚀}

Usage:

  • onBecomeObserved(observable, property?, listener: () => void): (() => void)
  • onBecomeUnobserved(observable, property?, listener: () => void): (() => void)

onBecomeObserved和onBecomeUnobserved方法可以给现有的可观察对象附加惰性行为或副作用。它们是MobX可观察系统的钩子并且 当可观察对象开始和停止被观察时,它们会得到通知。它们都返回一个用来取消listener的disposer函数。

在下面的示例中,我们只在实际使用被观察值时才使用它们来执行网络获取。

export class City {
    location
    temperature
    interval

    constructor(location) {
        makeAutoObservable(this, {
            resume: false,
            suspend: false
        })
        this.location = location
        // 只有在实际使用温度时才开始获取数据!
        onBecomeObserved(this, "temperature", this.resume)
        onBecomeUnobserved(this, "temperature", this.suspend)
    }

    resume = () => {
        log(`Resuming ${this.location}`)
        this.interval = setInterval(() => this.fetchTemperature(), 5000)
    }

    suspend = () => {
        log(`Suspending ${this.location}`)
        this.temperature = undefined
        clearInterval(this.interval)
    }

    fetchTemperature = flow(function* () {
        // 获取数据的逻辑...
    })
}
← 自定义 observables {🚀}集合工具 {🚀} →
MobX
Docs
About MobXThe gist of MobX
Community
GitHub discussions (NEW)Stack Overflow
More
Star