日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

一文教會你用redux實現(xiàn)computed計算屬性_React

作者:原罪 ? 更新時間: 2022-07-14 編程語言

前言

什么是computed計算屬性?它會根據(jù)所依賴的數(shù)據(jù)動態(tài)顯示新的計算結(jié)果, 該計算結(jié)果會被緩存起來。如果是Vue開發(fā)者,對這個功能并不陌生,而且很常用。對于React開發(fā)者,如果用過mobx,那其實也不陌生,一個裝飾器就生效了?。那如果是Redux呢??(沉默中。。。)有了,reselect嘛,哈哈?。啪,騙子,這是假的計算屬性,它要手動提供全部依賴,每個依賴都是一個函數(shù)回調(diào)確定依賴值,每次寫這么多代碼是有多想敲壞我的機(jī)械鍵盤(嘶吼)。

這么說,redux和計算屬性無緣?也不能這么說,辦法總比困難多。雖然redux是單向數(shù)據(jù)流,無法做響應(yīng)式操作,不過,我們可以創(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,因為兼容性不好。既然是前端的應(yīng)用,自然是要照顧到ES5的環(huán)境的,因此選擇defineProerty是個不錯的方案。

有了監(jiān)聽驅(qū)動,那監(jiān)聽豈不是易如反掌?

// 假設(shè)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時,構(gòu)造函數(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變量沒有任何關(guān)系了。

自動收集依賴已經(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下的最新值和舊值做對比,便可以知道這個依賴是否為臟值。這一步便是緩存的關(guān)鍵。

現(xiàn)在你相信reselect是騙子了吧,明明可以自動依賴,非要多寫幾行代碼增加心智負(fù)擔(dān)?拜托,不是每個人都需要KPI壓力的。

老師,我想直接在項目中使用上這個什么computed屬性,應(yīng)該去哪里找現(xiàn)成的呢?廢話,當(dāng)然是去山東找藍(lán)翔??纯此{(lá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

總結(jié)

原文鏈接:https://segmentfault.com/a/1190000041859375

欄目分類
最近更新