看一段源代码:
import { createSelector } from '@ngrx/store'; export interface State { evenNums: number[]; oddNums: number[]; } export const selectSumEvenNums = createSelector( (state: State) => state.evenNums, evenNums => evenNums.reduce((prev, curr) => prev + curr) ); export const selectSumOddNums = createSelector( (state: State) => state.oddNums, oddNums => oddNums.reduce((prev, curr) => prev + curr) ); export const selectTotal = createSelector( selectSumEvenNums, selectSumOddNums, (evenSum, oddSum) => evenSum + oddSum ); let result = selectTotal({ evenNums: [2, 4], oddNums: [1, 3], }); console.log('Ethan', result);
名为selectTotal的这个复合selector的消费方式很特别,直接传一个初始state进去即可:
第一次计算,因此缓存里没有lastResult,缓存没有命中,所以开始计算。
调用projectionFn.apply, 将arguments传入,进行计算:
已经在计算 6 + 4 了:
state就是传入的输入值:
先把偶数值全部求和: