了解下 MobX 概念

了解下 MobX 概念

Jul 19, 2021
前端, 系统设计

基本概念 #

  • observable 函数
    • 定义状态值
  • action 函数
    • 用于修改状态值
    • 接受一个函数,返回一个签名相同的函数,提供触发时调用。
  • derivations 派生,有两种:autoruncomputed
    • reactions - autorun()
      • 接受一个函数
      • 状态值发生改变后要执行的响应操作。
    • computed value - computed()
      • 接受一个函数,返回计算值对象。
      • 状态值发生改变时,计算值对象的值会自动更新。

observable #

MobX 中通过 observable 来定义可观察状态。

import { observable, autorun, computed, action } from "mobx";

// 定义状态
const store = observable({
  count: 0
});

derivations #

autorun #

MobX 中通过 autorun 来定义状态变化时要执行的响应操作,它接受一个函数,每当 observable 定义的状态发生变化时,MobX 都会立即执行该函数。

import { observable, autorun, computed, action } from "mobx"

autorun(() => {
  console.log("count:", store.count);
});

直接修改 store 或通过 action 都可以触发 autorun

const store = observable({
  a: 1
});
const increaseA = action(() => {
  store.a += 1;
});

store.a += 1
// 或者
increaseA();

computed #

状态值发生改变时,计算值对象的值会自动更新。

import { observable, autorun, computed, action } from "mobx"

const doubleCount = computed(() => 2 * store.count);

action #

不管 action 里面对 store 的修改次数有几次,一次 action 的调用最终只会触发一次 autorun 的执行。

const increaseA = action(() => {
  store.a += 1;
  store.a += 1;
});
increaseA();

和 react 结合 #

使用 mobx-react 包:

import React from "react";
import { observable } from "mobx";
import { observer } from "mobx-react";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.store = observable({
      count: 0
    });
  }

  render() {
    return (
      <button onClick={() => this.store.count++}>
        {this.store.count}
      </button>
    )
  }
}

export default observer(Counter);

参考 #

十分钟入门 MobX & React

MobX 简明教程

本文共 459 字,上次修改于 Feb 12, 2023,以 CC 署名-非商业性使用-禁止演绎 4.0 国际 协议进行许可。

相关文章

» 了解下 Redux 概念

» 浏览器中的 HTTP 缓存使用策略

» 前端的节流和防抖

» 说说实际工作中 GraphQL 的使用体验

» 实现限流的几种方案