Cheat Sheet速查表
跳转到主要内容

Mobx 速查表

本文根据 Devhints / Mobx 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2018-05-14。

属性

import {observable, computed} from 'mobx'

class Page {
  @observable title = ''
  @observable published = false
  @observable author = null

  @computed get authorName () {
    return this.author || 'Anonymous'
  }
}

操作

class Page {
  @action publish () {
    this.published = true
    // do ajax/async here if you like
  }
}

普通对象 (Plain objects)

const person = observable({
  name: 'Ella Fitzgerald'
})
const temp = observable(23)
temp.get()
temp.set(25)
temp.observe(...)

响应(Reactions)

导入

import {autorun, autorunAsync, when} from 'mobx'

autorun()

// Runs it, finds out what it accessed, then observe those
autorun(() => {
  console.log(page.title)
})

when()

class Foo {
  constructor () {
    when(
      () => !this.isVisible,
      () => this.doSomething())
  }
}

expr()

// A temporary computed value. Its result is cached.
render () {
  const isPublished = expr(() => page.published === true)
  if (isPublished) { ... }
}

修饰符

  • asMap(obj) - JS 映射(动态键)
  • asReference(fn) - 不要观察我
  • asStructure(obj) - JS 对象(作为 deepEqual 进行观察)
  • asFlat(array) - JS 数组(观察其子元素)

React

mobx-react

import { observer } from 'mobx-react'

@observer
class PageView extends React.Component {
  render () {
    return <div>{this.props.page.title}</div>
  }
}

<PageView page={page} />

函数式组件

import { observer } from 'mobx-react'

const PageView = observer(({page}) => {
  <div>{page.title}</div>
})

<PageView page={page} />

参考资料