MobX


https://blog.csdn.net/sinat_17775997/article/details/82772760


mobx 核心思想
  1. Actions 修改state
  2. state 更新触发 Computed values
  3. 组件触发 reactions
  4. reacttions 调用 Actions

State 是可观察和最低限度定义的,可以ishi任意类型
Computed values 是可以

class
实例成员类成员
实例身上可以使用的属性和方法publicstatic
constroctor
get/set

实例成员

类成员(实例成员
类成员
构造函数直接调用的属性和方法

class App{
	public a=1
	b=2
	public fn(){}
	构造器中的实例成员需要在参数内定义
	constructor(
		public c=3
		public fn=()=>{}
	){}
	
	存储器定义
	get fn(){}
	set fn(value){
		
	}
	类成员
	static a = 1
}
const app = new App()
安装

要想使用 mobx 第一步必须配置装饰器识别的环境。mobx 要用到装饰器 @ ,在原生中不识别这种语法。

  1. yarn eject
  2. yarn add mobx mobx-react:这两个是必须的包,与装饰器无关
  3. yarn add babel-plugin-transform-decorators-legacy -D
  4. yarn add @babel/preset-env -D
  5. yarn add babel-plugin-transform-class-properties -D
  6. yarn add @babel/plugin-proposal-decorators -D
  7. 配置 package.json 中的 bable
"babel": {
  "plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ],
    注意: class 和 properties 顺序不可颠倒
    "transform-class-properties"
  ],
  "presets": [
    "react-app",
    "@babel/preset-env"
  ]
},
使用
  1. 项目入口文件
import {Provider} from 'mobx-react'
import store from './store'

ReactDOM.render(
<Provider store={store}>
  <App />
</Provider>
, document.getElementById('root'));
  1. 打造 mobx 数据包
observable 观察者
actions 异步修改数据

imorpt { observable, action, computed }  from 'mobx'

class Home{
@observable	定义,监听 age 数据
  age = 18
@computed    age 改变自动触发
  get doubleAge(){}
  }

this 会丢失,需要写成箭头函数
@action
  change = () => {
   this.age++
  }
 
或者可以这么写,在 @action.bound 内 this 永远正确
@action.bound
  change(){
	this.age++
  }
  
const home = new Home()
export default home

  1. 组件内注入使用
数据通过 this.props.store 访问
方法通过 this.props.store 原型对象内有 action 等

import React from 'react'
import { inject, observer } from 'mobx-react'

@inject('store')		注入 store
@observer				自动订阅,如果不写这个数据改变,视图不更新
class Mine extends React.Component{
  change = () => {
    this.props.store.home.change()
  }
  render(){
    return(
      <div>
        <p>age:{this.props.store.home.age}</p>
        <button onClick={this.props.store.home.change.bind(this)}>长大</button>
        <button onClick={this.change()}>长大</button>
      </div>
    )
  }
}

export default Mine

注意:
1.observable 从 mobx 引入,observer 从 mobx-react 引入

observerobservable
import { inject, observer } from 'mobx-react'imorpt { observable, action, computed } from 'mobx'
组件.jsstore/index.js

2.如果写了@observer ,那么 computed 失效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值