头图

The selector returned by NgRx Store createSelector executes the single-step debugging of the access logic

JerryWang_汪子熙
中文

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":

阅读 394

Jerry Wang的SAP技术专栏
SAP成都研究院开发专家,SAP社区导师,SAP中国技术大使

Jerry 2007年从电子科技大学计算机专业硕士毕业后进入SAP成都研究院工作至今, SAP社区导师,SAP中国技术...

781 声望
1k 粉丝
0 条评论

Jerry 2007年从电子科技大学计算机专业硕士毕业后进入SAP成都研究院工作至今, SAP社区导师,SAP中国技术...

781 声望
1k 粉丝
文章目录
宣传栏