我們是袋鼠雲數棧 UED 團隊,致力於打造優秀的一站式數據中台產品。我們始終保持工匠精神,探索前端道路,為社區積累並傳播經驗價值。 本文作者:霜序(LuckyFBB) 前言 在之前的文章中,我們講述了 React 的數據流管理,從 props → context → Redux,以及 Redux 相 ...
我們是袋鼠雲數棧 UED 團隊,致力於打造優秀的一站式數據中台產品。我們始終保持工匠精神,探索前端道路,為社區積累並傳播經驗價值。
本文作者:霜序(LuckyFBB)
前言
在之前的文章中,我們講述了 React 的數據流管理,從 props → context → Redux,以及 Redux 相關的三方庫 React-Redux。
那其實說到 React 的狀態管理器,除了 Redux 之外,Mobx 也是應用較多的管理方案。Mobx 是一個響應式庫,在某種程度上可以看作沒有模版的 Vue,兩者的原理差不多
先看一下 Mobx 的簡單使用,線上示例
export class TodoList {
@observable todos = [];
@computed get getUndoCount() {
return this.todos.filter((todo) => !todo.done).length;
}
@action add(task) {
this.todos.push({ task, done: false });
}
@action delete(index) {
this.todos.splice(index, 1);
}
}
Mobx 藉助於裝飾器來實現,使得代碼更加簡潔。使用了可觀察對象,Mobx 可以直接修改狀態,不用像 Redux 那樣寫 actions/reducers。Redux 是遵循 setState 的流程,MobX就是幹掉了 setState 的機制
通過響應式編程使得狀態管理變得簡單和可擴展。Mobx v5 版本利用 ES6 的proxy
來追蹤屬性,以前的舊版本通過Object.defineProperty
實現的。通過隱式訂閱,自動追蹤被監聽的對象變化
Mobx 的執行流程,一張官網結合上述例子的圖
MobX將應用變為響應式可歸納為下麵三個步驟
-
定義狀態並使其可觀察
使用
observable
對存儲的數據結構成為可觀察狀態 -
創建視圖以響應狀態的變化
使用
observer
來監聽視圖,如果用到的數據發生改變視圖會自動更新 -
更改狀態
使用
action
來定義修改狀態的方法
Mobx核心概念
observable
給數據對象添加可觀察的功能,支持任何的數據結構
const todos = observable([{
task: "Learn Mobx",
done: false
}])
// 更多的採用裝飾器的寫法
class Store {
@observable todos = [{
task: "Learn Mobx",
done: false
}]
}
computed
在 Redux 中,我們需要計算已經 completeTodo 和 unCompleteTodo,我們可以採用:在 mapStateToProps 中,通過 allTodos 過濾出對應的值,線上示例
const mapStateToProps = (state) => {
const { visibilityFilter } = state;
const todos = getTodosByVisibilityFilter(state, visibilityFilter);
return { todos };
};
在 Mobx 中可以定義相關數據發生變化時自動更新的值,通過@computed
調用getter
/setter
函數進行變更
一旦 todos 的發生改變,getUndoCount 就會自動計算
export class TodoList {
@observable todos = [];
@computed get getUndo() {
return this.todos.filter((todo) => !todo.done)
}
@computed get getCompleteTodo() {
return this.todos.filter((todo) => todo.done)
}
}
action
動作是任何用來修改狀態的東西。MobX 中的 action 不像 redux 中是必需的,把一些修改 state 的操作都規範使用 action 做標註。
在 MobX 中可以隨意更改todos.push({ title:'coding', done: false })
,state 也是可以有作用的,但是這樣雜亂無章不好定位是哪裡觸發了 state 的變化,建議在任何更新observable
或者有副作用的函數上使用 actions。
在嚴格模式useStrict(true)
下,強制使用 action
// 非action使用
<button
onClick={() => todoList.todos.push({ task: this.inputRef.value, done: false })}
>
Add New Todo
</button>
// action使用
<button
onClick={() => todoList.add(this.inputRef.value)}
>
Add New Todo
</button>
class TodoList {
@action add(task) {
this.todos.push({ task, done: false });
}
}
Reactions
計算值 computed 是自動響應狀態變化的值。反應是自動響應狀態變化的副作用,反應可以確保相關狀態變化時指定的副作用執行。
-
autorun
autorun
負責運行所提供的sideEffect
並追蹤在sideEffect
運行期間訪問過的observable
的狀態接受一個函數
sideEffect
,當這個函數中依賴的可觀察屬性發生變化的時候,autorun
裡面的函數就會被觸發。除此之外,autorun
裡面的函數在第一次會立即執行一次。autorun(() => { console.log("Current name : " + this.props.myName.name); }); // 追蹤函數外的間接引用不會生效 const name = this.props.myName.name; autorun(() => { console.log("Current name : " + name); });
-
reaction
reaction
是autorun
的變種,在如何追蹤observable
方面給予了更細粒度的控制。 它接收兩個函數,第一個是追蹤並返回數據,該數據用作第二個函數,也就是副作用的輸入。autorun 會立即執行一次,但是 reaction 不會
reaction( () => this.props.todoList.getUndoCount, (data) => { console.log("Current count : ", data); } );
observer
使用 Redux 時,我們會引入 React-Redux 的 connect 函數,使得我們的組件能夠通過 props 獲取到 store 中的數據
在 Mobx 中也是一樣的道理,我們需要引入 observer 將組件變為響應式組件
包裹 React 組件的高階組件,在組件的 render 函數中任何使用的observable
發生變化時,組件都會調用 render 重新渲染,更新 UI
⚠️ 不要放在頂層 Page,如果一個 state 改變,整個 Page 都會 render,所以 observer 儘量去包裹小組件,組件越小重新渲染的變化就越小
@observer
export default class TodoListView extends Component {
render() {
const { todoList } = this.props;
return (
<div className="todoView">
<div className="todoView__list">
{todoList.todos.map((todo, index) => (
<TodoItem
key={index}
todo={todo}
onDelete={() => todoList.delete(index)}
/>
))}
</div>
</div>
);
}
}
Mobx原理實現
前文中提到 Mobx 實現響應式數據,採用了Object.defineProperty
或者Proxy
上面講述到使用 autorun 會在第一次執行並且依賴的屬性變化時也會執行。
const user = observable({ name: "FBB", age: 24 })
autorun(() => {
console.log(user.name)
})
當我們使用 observable 創建了一個可觀察對象user
,autorun 就會去監聽user.name
是否發生了改變。等於user.name
被 autorun 監控了,一旦有任何變化就要去通知它
user.name.watchers.push(watch)
// 一旦user的數據發生了改變就要去通知觀察者
user.name.watchers.forEach(watch => watch())
observable
裝飾器一般接受三個參數: 目標對象、屬性、屬性描述符
通過上面的分析,通過 observable 創建的對象都是可觀察的,也就是創建對象的每個屬性都需要被觀察
每一個被觀察對象都需要有自己的訂閱方法數組
const counter = observable({ count: 0 })
const user = observable({ name: "FBB", age: 20 })
autorun(function func1() {
console.log(`${user.name} and ${counter.count}`)
})
autorun(function func2() {
console.log(user.name)
})
對於上述代碼來說,counter.count 的 watchers 只有 func1,user.name 的 watchers 則有 func1/func2
實現一下觀察者類 Watcher,藉助 shortid 來區分不同的觀察者實例
class Watcher {
id: string
value: any;
constructor(v: any, property: string) {
this.id = `ob_${property}_${shortid()}`;
this.value = v;
}
// 調用get時,收集所有觀察者
collect() {
dependenceManager.collect(this.id);
return this.value;
}
// 調用set時,通知所有觀察者
notify(v: any) {
this.value = v;
dependenceManager.notify(this.id);
}
}
實現一個簡單的裝飾器,需要攔截我們屬性的 get/set 方法,並且使用 Object.defineProperty 進行深度攔截
export function observable(target: any, name: any, descriptor: { initializer: () => any; }) {
const v = descriptor.initializer();
createDeepWatcher(v)
const watcher = new Watcher(v, name);
return {
enumerable: true,
configurable: true,
get: function () {
return watcher.collect();
},
set: function (v: any) {
return watcher.notify(v);
}
};
};
function createDeepWatcher(target: any) {
if (typeof target === "object") {
for (let property in target) {
if (target.hasOwnProperty(property)) {
const watcher = new Watcher(target[property], property);
Object.defineProperty(target, property, {
get() {
return watcher.collect();
},
set(value) {
return watcher.notify(value);
}
});
createDeepWatcher(target[property])
}
}
}
}
在上面 Watcher 類中的get/set
中調用了 dependenceManager 的方法還未寫完。在調用屬性的get
方法時,會將函數收集到當前 id 的 watchers 中,調用屬性的set
方法則是去通知所有的 watchers,觸發對應收集函數
那這這裡其實我們還需要藉助一個類,也就是依賴收集類DependenceManager
,馬上就會實現
autorun
前面說到 autorun 會立即執行一次,並且會將函數收集起來,存儲到對應的observable.id
的 watchers 中。autorun 實現了收集依賴,執行對應函數。再執行對應函數的時候,會調用到對應observable
對象的get
方法,來收集依賴
export default function autorun(handler) {
dependenceManager.beginCollect(handler)
handler()
dependenceManager.endCollect()
}
實現DependenceManager
類:
- beginCollect: 標識開始收集依賴,將依賴函數存到一個類全局變數中
- collect(id): 調用
get
方法時,將依賴函數放到存入到對應 id 的依賴數組中 - notify: 當執行
set
的時候,根據 id 來執行數組中的函數依賴 - endCollect: 清除剛開始的函數依賴,以便於下一次收集
class DependenceManager {
_store: any = {}
static Dep: any;
beginCollect(handler: () => void) {
DependenceManager.Dep = handler
}
collect(id: string) {
if (DependenceManager.Dep) {
this._store[id] = this._store[id] || {}
this._store[id].watchers = this._store[id].watchers || []
if (!this._store[id].watchers.includes(DependenceManager.Dep))
this._store[id].watchers.push(DependenceManager.Dep);
}
}
notify(id: string) {
const store = this._store[id];
if (store && store.watchers) {
store.watchers.forEach((watch: () => void) => {
watch.call(this);
})
}
}
endCollect() {
DependenceManager.Dep = null
}
}
一個簡單的 Mobx 框架都搭建好了~
computed
computed 的三個特點:
- computed 方法是一個 get 方法
- computed 會根據依賴的屬性重新計算值
- 依賴 computed 的函數也會被重新執行
發現 computed 的實現大致和 observable 相似,從以上特點可以推斷出 computed 需要兩次收集依賴,一次是收集 computed 所依賴的屬性,一次是依賴 computed 的函數
首先定義一個 computed 方法,是一個裝飾器
export function computed(target: any, name: any, descriptor: any) {
const getter = descriptor.get; // get 函數
const _computed = new ComputedWatcher(target, getter);
return {
enumerable: true,
configurable: true,
get: function () {
_computed.target = this
return _computed.get();
}
};
}
實現 ComputedWatcher 類,和 Watcher 類差不多。在執行 get 方法的時候,我們和之前一樣,去收集一下依賴 computed 的函數,豐富 get 方法
class ComputedWatcher {
// 標識是否綁定過recomputed依賴,只需要綁定一次
hasBindAutoReCompute: boolean | undefined;
value: any;
// 綁定recompute 和 內部涉及到的觀察值的關係
_bindAutoReCompute() {
if (!this.hasBindAutoReCompute) {
this.hasBindAutoReCompute = true;
dependenceManager.beginCollect(this._reComputed, this);
this._reComputed();
dependenceManager.endCollect();
}
}
// 依賴屬性變化時調用的函數
_reComputed() {
this.value = this.getter.call(this.target);
dependenceManager.notify(this.id);
}
// 提供給外部調用時收集依賴使用
get() {
this._bindAutoReCompute()
dependenceManager.collect(this.id);
return this.value
}
}
observer
observer 相對實現會簡單一點,其實是利用 React 的 render 函數對依賴進行收集,我們採用在 componnetDidMount 中調用 autorun 方法
export function observer(target: any) {
const componentDidMount = target.prototype.componentDidMount;
target.prototype.componentDidMount = function () {
componentDidMount && componentDidMount.call(this);
autorun(() => {
this.render();
this.forceUpdate();
});
};
}
至此一個簡單的 Mobx 就實現了,線上代碼地址
文章中使用的 Object.defineProperty 實現,Proxy 實現差不多,線上代碼地址
Mobx vs Redux
-
數據流
Mobx 和 Redux 都是單向數據流,都通過 action 觸發全局 state 更新,再通知視圖
Redux 的數據流
Mobx 的數據流
-
修改數據的方式
-
他們修改狀態的方式是不同的,Redux 每一次都返回了新的 state。Mobx 每次修改的都是同一個狀態對象,基於響應式原理,
get
時收集依賴,set
時通知所有的依賴 -
當 state 發生改變時,Redux 會通知所有使用 connect 包裹的組件;Mobx 由於收集了每個屬性的依賴,能夠精準通知
-
當我們使用 Redux 來修改數據時採用的是 reducer 函數,函數式編程思想;Mobx 使用的則是面向對象代理的方式
-
-
Store 的區別
- Redux 是單一數據源,採用集中管理的模式,並且數據均是普通的 JavaScript 對象。state 數據可讀不可寫,只有通過 reducer 來改變
- Mobx 是多數據源模式,並且數據是經過
observable
包裹的 JavaScript 對象。state 既可讀又可寫,在非嚴格模式下,action 不是必須的,可以直接賦值
一些補充
observable 使用函數式寫法
在採用的 proxy 寫法中,可以劫持到一個對象,將對象存在 weakMap 中,每次觸發對應事件去獲取相關信息
Proxy 監聽 Map/Set
總結
本文從 Mobx 的簡單示例開始,講述了一下 Mobx 的執行流程,引入了對應的核心概念,然後從零開始實現了一個簡版的 Mobx,最後將 Mobx 和 Redux 做了一個簡單的對比
參考鏈接