mobxjs flow
mobx減化redux,它是一個觀察者模式。當observable的state有變化時,就會觸發反應後續動作。MobX推薦使用decorators (@xxxxxx)寫法可使程式更加簡潔易讀,如果你要使用ES5語法寫也可以。但在使用decorators前記得裝plugin,詳情請參考官網。
撰寫一個簡單的counter範例,可以比較我之前寫的react-redux-counter,看看redux與MobX的差異性。
@observable:觀察的state
@action.bound:只有action才能更改state
@computed:計算state值
src/CounterStore.js
import { observable, action, computed } from 'mobx';
class CountStore {
@observable num = 0;
@computed get getDoubleCount() {
return this.num * 2;
}
@action.bound onIncrement() {
this.num = this.num + 1;
}
@action.bound onDecrement() {
this.num = this.num - 1;
}
}
export default CountStore;
@inject:注入Provider傳的store
src/Counter.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
@inject('count')
@observer
class Counter extends Component {
render() {
const { count } = this.props;
return (
<div>
<p>
Count: {count.num}
</p>
<p>
Double count: {count.getDoubleCount}
</p>
<div>
<button onClick={count.onIncrement}>+1</button>
<button onClick={count.onDecrement}>-1</button>
</div>
</div>
);
}
}
export default Counter;
Provider傳遞store讓子元件可以使用
src/index.js
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'mobx-react';
import Counter from './Counter';
import CountStore from './CountStore';
const stores = {
count: new CountStore(),
};
render(
<Provider {...stores}>
<Counter />
</Provider>,
document.getElementById('app'),
);
輸出畫面
Redux vs MobX
如果用counter範例來比較redux與MobX,MobX的確簡化很多程式碼。但redux推出比較早,相關套件、周遭支援度、網路資源比較多,而MobX包裝很多東西看似簡單實際應用不知如何,簡單範例踩雷的機會比較小,待實作專案才會知道。如果有需要把UI與資料邏輯拆開,可以評估redux與MobX看看。
github repository react-mobx-counter
https://github.com/kwon44/react-mobx-counter
參考資料
MobX
https://github.com/mobxjs
MobX Doc
https://mobx.js.org/index.html
Simple MobX
https://bumbu.github.io/simple-mobx/
How to (not) use decorators
https://mobx.js.org/best/decorators.html