Test source code:
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 7
console.log(selectTotal(state)); // does not compute the sum of 3 & 4. selectTotal instead returns the memoized value of 7
}
}
First execute the first selector call in the constructor.
The function body of selectTotal is the memoized function returned by createSelector:
Because it is the first call, lastArguments is undefined, so projectionFn is executed:
The addition operation defined in projection will not be called immediately:
Here we can't see the projectionFn function specified when createSelector is passed in our application.
selectors is an array, which stores the pure functions passed in by application developers:
Call the map method that comes with the array, and first calculate the input parameters required for projection calculation:
Here fn is the first element of the selectors array:
Get 3:
By analogy, the second parameter 4:
3 and 4 are the input parameters for finally calling projectionFn with memory function:
This is the memoized function body we already know. You can refer to Jerry's previous article: NgRx Store createSelector single-step debugging and source code analysis .
The projector is the last pure function passed in by createSelector, that is, the function that performs the addition operation:
Perform a summation operation:
Cache the called input parameters 3 and 4. The calculation result 7 is also cached together:
In the second execution, because the input parameters have not changed, they are still 3 and 4, so 7 is directly taken from the cached result and returned.
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。