一共有两个套件:
dob
优势,就是由于使用了 proxy,支持跟踪不存在的变量,比如:
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 已经被完美实现了。
dob-react
和 mobx-react 别无二致,优化点在于,不再区分 observer 与 inject,所有绑定与注入集成在一个装饰器(因为有依赖追踪,所以全量注入没有性能问题,这很 DX)
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,所有变量自动开启跟踪。
完整用法
yarn add dob dependency-inject --save
store.ts
:
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
:
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'))