使用 proxy 实现的 mobx - dob 介绍

一共有两个套件: react

dob

优点,就是因为使用了 proxy,支持跟踪不存在的变量,好比:git

import { observe, observable } from 'dob'

const dynamicObj = observable({
    a: 1
})

observe(() => {
    console.log('dynamicObj.b change to', dynamicObj.b) 
})

// 如今要修改 b 了,b 以前不存在
dynamicObj.b = 2 // dynamicObj.b change to 2复制代码

很方便吧,实现了 mobx 求之不得的夙愿,至今为止但愿实现的 dob-react 已经被完美实现了。github

dob-react

和 mobx-react 别无二致,优化点在于,再也不区分 observer 与 inject,全部绑定与注入集成在一个装饰器(由于有依赖追踪,因此全量注入没有性能问题,这很 DX)typescript

import { Provider, Connect } from 'dob-react'

@Connect
class App extends React.Component <any, any> {
    render() {
        return (
            <span>{this.props.store.name}</span>
        )
    }
}

ReactDOM.render(
    <Provider store={{ name: 'bob' }}>
        <App />
    </Provider>
, document.getElementById('react-dom'))复制代码

第二个优化点,在于不须要手动指定 @Observerable,全部变量自动开启跟踪。bash

完整用法

yarn add dob dependency-inject --save复制代码

store.ts:app

import { inject, Container } from 'dependency-inject'
import { Action } from 'dob'

export class Store {
    name = 'bob'
}

export class Action {
    @inject(Store) store: Store

    @Action setName (name: string) {
        this.store.name = name
    }
}

const container = new Container()
container.set(Store, new Store())
container.set(Action, new Action())

export { container }复制代码

app.ts:dom

import { Provider, Connect } from 'dob-react'
import { Store, Action, container } from './store'

@Connect
class App extends React.Component <any, any> {
    componentWillMount () {
        this.props.action.setName('nick')
    }

    render() {
        return (
            <span>{this.props.name}</span>
        )
    }
}

ReactDOM.render(
    <Provider store={container.get(Store)} action={container.get(Action)}>
        <App />
    </Provider>
, document.getElementById('react-dom'))复制代码
相关文章
相关标签/搜索