JSPM

mota

8.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 638
  • Score
    100M100P100Q86937F
  • License MIT

An extremely lightweight and responsive state management library

Package Exports

  • mota
  • mota/dist/mota-cjs.js
  • mota/dist/mota-es.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (mota) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

logo

npm NPM Version Build Status Coverage Status npm

Overview

Mota 是一个「极轻量、可响应」的状态管理库,不足 5KB,开发人员可利用它编写「几乎框架无关的纯 JS/TS 业务模型」,然后通过 Mota 简便的让 React 组件响应模型的变化。

Install

通过 npm 安装,如下

$ npm install mota --save

Usage

import { Component } from "react";
import { observable, observer, useWatch, watch } from "mota";

// 编写一个模型类
@observable
class DemoModel {
  count = 0;
  add = ()=>{
    this.count += 1;
  }
}

// 创建一个模型实例
const demo = DemoModel();

// 直接声明一个对象
const info = observable({
  title: 'test',
});

// 在类组件中使用一
@observer
class DemoView1 extends Component{
  // 创建一个组件实例对应和模型实例
  model = new DemoModel();
  render() {
    const {count, add} = this.model
    return (
      <div>
        <div>{info.title}</div>
        <div>{count}</div>
        <button onClick={add}>Add</button>
      </div>
    );
  }
}

// 在类组件中使用二
@observer
class DemoView2 extends Component{
  render() {
    return (
      <div>
        <div>{info.title}</div>
        <div>{demo.count}</div>
      </div>
    );
  }
}

// 在函数组件中使用
const DemoView3 = observer(()=>{
  return (
    <div>{model.count}</div>
  )
});

// 监听数据变化
const DemoView4 = ()=>{
  // useWatch 的第一个参数是计算函数,
  // 计处函数的返回结果发生变化时, 将执行第二个处理函数
  useWatch(()=>model.count,()=>{
    console.log('model.count', model.count);
  });
  return (
    <div>{model.count}</div>
  )
};

// 在任意地方使用 watch 
const destroy = watch(()=>model.count,()=>{
  console.log('model.count', model.count);
});

// 取消观察
destroy();

// 在类组件中使用 watch
class DemoView5 extends Component {
  componentDidMount(){
    this.destroyWatch = watch(()=>model.count,()=>{
     console.log('model.count', model.count);
    });
  }
  componentWillUnmount(){
    if(this.destroyWatch) this.destroyWatch();
  }
}