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.
Inside createSelector:
function createSelector(...input) {
return createSelectorFactory(defaultMemoize)(...input);
}
defaultMemoize returns an object, each field points to a function:
As input parameters, I passed in three pure functions, that is, functions that can be executed repeatedly without side effects. These three pure functions are maintained in an array:
Enter the function body returned by createSelectorFactory:
As can be seen from the source code, the last one of the variable number of parameters received by createSelector is treated as a projector, and the rest are treated as selectors.
Discuss in the following situations:
(1) The first execution, lastArguments undefined, enter the IF branch, execute projection, save the result, and return.
(2) If it is repeated execution and the input parameters have not changed, it will directly return to the result of the previous execution
(3) At this point, if the execution is repeated, and the parameters have changed, then re-execute the projection
(4) If the result of the second execution is the same as the previous execution, return to the previous result
What createSelector finally returns is a selector with memory function:
If you want to debug in the future, remember that the approximate location of the code is 970, and search for the keyword memoized.
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。