一文教會你用redux實現(xiàn)computed計算屬性
前言
什么是computed計算屬性?它會根據(jù)所依賴的數(shù)據(jù)動態(tài)顯示新的計算結果, 該計算結果會被緩存起來。如果是Vue開發(fā)者,對這個功能并不陌生,而且很常用。對于React開發(fā)者,如果用過mobx,那其實也不陌生,一個裝飾器就生效了??。那如果是Redux呢??(沉默中。。。)有了,reselect嘛,哈哈??。啪,騙子,這是假的計算屬性,它要手動提供全部依賴,每個依賴都是一個函數(shù)回調確定依賴值,每次寫這么多代碼是有多想敲壞我的機械鍵盤(嘶吼)。
這么說,redux和計算屬性無緣?也不能這么說,辦法總比困難多。雖然redux是單向數(shù)據(jù)流,無法做響應式操作,不過,我們可以創(chuàng)造出一個監(jiān)聽對象
import { Store } from 'redux';
const collector = [];
class ObjectDeps {
protected readonly deps: string[];
protected readonly name: string;
protected readonly store: Store;
protected snapshot: any;
constructor(store: Store, name: string, deps: string[] = []) {
this.store = store;
this.name = name;
this.deps = deps;
collector.push(this);
}
proxy(currentState) {
if (state === null || typeof state != 'object') return state;
const proxyData = Array.isArray(state) : [] : {};
const currentDeps = this.deps.slice();
const keys = Object.keys(currentState);
for (let i = keys.length; i-- > 0; ) {
const key = keys[i]!;
Object.defineProperty(proxyData, key, {
enumerable: true,
get: () => {
if (visited) {
return new ObjectDeps(
this.store,
this.name,
currentDeps.slice(),
).proxy(currentState)[key];
}
visited = true;
this.deps.push(key);
return this.proxy((this.snapshot = currentState[key]));
},
});
}
}
}樸實無華,沒有基于ES6的Proxy,因為兼容性不好。既然是前端的應用,自然是要照顧到ES5的環(huán)境的,因此選擇defineProerty是個不錯的方案。
有了監(jiān)聽驅動,那監(jiān)聽豈不是易如反掌?
// 假設user里的對象為:{ firstName: 'lady', lastName: 'gaga' }
const userState = store.getState()['user'];
function computedFullName() {
const proxy = new ObjectDeps(store, 'user').proxy(userState);
return proxy.firstName + '-' + proxy.lastName;
}
const fullname = computedFullName();現(xiàn)在我們看看collector里收集到多少個依賴
console.log(collector); // [ ObjectDeps, ObjectDeps ]
不錯,兩條依賴,第一條的deps鏈為['user', 'firstName'],第二條為['user', 'lastName']。
原理分析:
- 每次創(chuàng)建proxy時,構造函數(shù)均會執(zhí)行collector.push(this)向采集器加入自己。
- proxy訪問firstName時,其實訪問的是getter,getter中有一條this.deps.push(key)立即收集依賴,并返回下一級的proxy值。以此類推,即使是proxy.a.b.c.d這種深度操作也來者不拒,因為每次訪問下一級都能收集依賴并合并到deps數(shù)組中。
- proxy訪問lastName時,由于proxy實例其實已經(jīng)被firstName占用了(通過visited變量判斷),所以getter邏輯中會直接返回一個新的ObjectDeps實例,此時lastName已經(jīng)和我們看到的proxy變量沒有任何關系了。
自動收集依賴已經(jīng)實現(xiàn)了,我們試一下如何緩存屬性
class ObjectDeps {
protected snapshot: any;
proxy() {...}
isDirty() {
return this.snapshot !== this.getSnapshot();
}
protected getSnapshot() {
const deps = this.deps;
let snapshot = this.store.getState();
for (let i = 0; i < deps.length; ++i) {
if (snapshot == null || typeof snapshot !== 'object') {
break;
}
snapshot = snapshot[deps[i]!];
}
return snapshot;
}
}通過isDirty()的判斷,即再次獲得deps下的最新值和舊值做對比,便可以知道這個依賴是否為臟值。這一步便是緩存的關鍵。
現(xiàn)在你相信reselect是騙子了吧,明明可以自動依賴,非要多寫幾行代碼增加心智負擔?拜托,不是每個人都需要KPI壓力的。
老師,我想直接在項目中使用上這個什么computed屬性,應該去哪里找現(xiàn)成的呢?廢話,當然是去山東找藍翔??纯此{翔大法:
import { defineModel, useComputed } from 'foca';
export const userModel = defineModel('user', {
initialState: {
firstName: 'lady',
lastName: 'gaga',
},
computed: {
// 清爽
fullName() {
return this.state.firstName + '-' + this.state.lastName;
},
},
});
// App.tsx
const App: FC = () => {
const fullName = useComputed(userModel.fullName);
return <div>{fullName}</div>;
};嗯?剛剛發(fā)生了什么,好像看到dva飛過去?飛你個頭,是哥寫的React狀態(tài)管理庫foca,基于redux和react-redux,剛才的computed解析就是從里面摘抄的(具體實現(xiàn)邏輯請看這里)。雖然是個軟廣告,不過redux也算是支持computed了,各位大佬就不要天天噴redux這個不好那個不好了行吧??,二次封裝才是真愛。
人生苦短,手握神器,少寫代碼,早點下班最要緊:https://github.com/foca-js/foca
總結
到此這篇關于用redux實現(xiàn)computed計算屬性的文章就介紹到這了,更多相關redux實現(xiàn)computed計算屬性內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于react hook useState連續(xù)更新對象的問題
這篇文章主要介紹了關于react hook useState連續(xù)更新對象的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
詳解React setState數(shù)據(jù)更新機制
這篇文章主要介紹了React setState數(shù)據(jù)更新機制的相關資料,幫助大家更好的理解和學習使用React框架,感興趣的朋友可以了解下2021-04-04
react實現(xiàn)一個優(yōu)雅的圖片占位模塊組件詳解
這篇文章主要給大家介紹了關于react如何實現(xiàn)一個還算優(yōu)雅的占位模塊圖片組件的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-10-10

