NgRx Store createSelector 返回的 selector 执行取数逻辑的单步调试
測試源代碼:
import { Component } from '@angular/core'; import { createSelector } from '@ngrx/store';export interface State {counter1: number;counter2: number; }export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector(selectCounter1,selectCounter2,(counter1, counter2) => counter1 + counter2 ); // selectTotal has a memoized value of null, because it has not yet been invoked.let state = { counter1: 3, counter2: 4 };@Component({selector: 'selector',template: '' }) export class SelectorComponent{constructor(){console.log(selectTotal(state)); // computes the sum of 3 & 4, returning 7. selectTotal now has a memoized value of 7console.log(selectTotal(state)); // does not compute the sum of 3 & 4. selectTotal instead returns the memoized value of 7} }首先執行構造函數里第一條 selector 調用。
selectTotal 的函數體就是 createSelector 返回的 memoized 函數:
因為是第一次調用,lastArguments 為 undefined,因此執行 projectionFn:
還不會馬上調用到我們在 projection 里定義的加法運算:
 
這里還看不到我們應用程序里傳入 createSelector 時指定的 projectionFn 函數。
selectors 是數組,里面存放了應用開發人員傳入的純函數:
調用數組自帶的 map 方法,首先把 projection 計算所需的輸入參數計算出來:
此處 fn 即 selectors 數組第一個元素:
 
得到3:
 
依次類推,第二個參數4:
 
3和4即為最終調用帶有記憶功能的 projectionFn 的輸入參數:
 
這就是我們已經熟知的 memoized 函數體了。可以參考 Jerry 之前的文章:NgRx Store createSelector 的單步調試和源代碼分析。
projector 就是之前 createSelector 傳入的純函數的最后一個,即執行加法運算的 函數:
執行求和運算:
 
將調用的輸入參數3和4緩存起來。一并緩存的還有計算結果7:
 
第二次執行時,因為輸入參數未變,仍然是3和4,故直接從緩存結果里取出7,返回之。
 
更多Jerry的原創文章,盡在:“汪子熙”:
 
總結
以上是生活随笔為你收集整理的NgRx Store createSelector 返回的 selector 执行取数逻辑的单步调试的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 云顶之弈大元素使拉克丝图鉴 S2全英雄技
- 下一篇: SAP Commerce Cloud S
