MobX 中文网

MobX 中文网

  • API 文档
  • Nodejs.cn 旗下网站

›提示与技巧

介绍

  • 关于 MobX
  • 关于本文档
  • 安装
  • MobX 的要点

MobX 核心

  • 可观察状态
  • 操作
  • 计算
  • 反应 {🚀}
  • API

MobX 与 React

  • React 集成
  • React 优化 {🚀}

提示与技巧

  • 定义数据存储
  • 了解反应性
  • 子类化
  • 分析反应性 {🚀}
  • 使用参数进行计算 {🚀}
  • MobX-utils {🚀}
  • 自定义可观察值 {🚀}
  • 惰性可观察量 {🚀}
  • 集合实用程序 {🚀}
  • 拦截和观察 {🚀}

微调

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

创建惰性可观察量 {🚀}

¥Creating lazy observables {🚀}

用法:

¥Usage:

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

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

函数 onBecomeObserved 和 onBecomeUnobserved 可用于将惰性行为或副作用附加到现有可观察量。它们连接到 MobX 的可观察性系统,并在可观察对象开始和停止被观察时收到通知。它们都返回一个分离监听器的处理程序函数。

¥Functions onBecomeObserved and onBecomeUnobserved can be used to attach lazy behavior or side effects to existing observables. They hook into the observability system of MobX and get notified when an observable starts and stops becoming observed. They both return a disposer function that detaches the listener.

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

¥In the example below we use them to perform network fetches only when the observed value is actually in use.

export class City {
    location
    temperature
    interval

    constructor(location) {
        makeAutoObservable(this, {
            resume: false,
            suspend: false
        })
        this.location = location
        // Only start data fetching if temperature is actually used!
        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* () {
        // Data fetching logic...
    })
}
← 自定义可观察值 {🚀}集合实用程序 {🚀} →
MobX v6.13 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站