Mobx 4.x-5.x
mobx核心概念:
- mobx.observable
将对象的属性变为可观察的属性
// 原写法
observable({
count: 0
});
//装饰器写法
class Store {
@observable count = 0
}
- mobx.action
用来定义更改状态的函数
// 原写法
action(() => {
store.count++
})
//装饰器写法
@action setCount = () => {
this.count++
}
3.计算属性
// 原写法
const orderLine = observable.object({
price: 0,
amount: 1,
get total() {
return this.price * this.amount
},
set total(total) {
this.price = total / this.amount // 从 total 中推导出 price
}
})
//装饰器写法
class Foo {
@observable length = 2;
@computed get squared() {
return this.length * this.length;
}
set squared(value) { // 这是一个自动的动作,不需要注解
this.length = Math.sqrt(value);
}
mobx-react核心概念:
- observer
将 React 组件转变成响应式组件
// 原写法
function Home () {
return (
...
)
}
export default observer(Home)
//装饰器写法
@observer
class Home extends React.Component{
render () {
return (
...
)
}
}
版本兼容性
Mobx5
需要配合react16.x
使用,mobx5搭配react17会报错。
babelrc语法兼容
"plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }],