头图

NgRX Store models state as a single simple JavaScript object within the Store. State is immutable or read-only. This means that there is no direct Store API to change state objects within the Store. An example of such a state object can be represented as:

 const state = {
    developer: []
};

The Store stores many slices of application state, called State.

Actions

In order to update the state in the Store, the application needs to schedule an Action. A reducer, also known as a pure function, captures this action, performs an update on the state, and returns a 新的 modified immutable state object .

An example of an action:

 const action = {
    type: 'ADD_DEVELOPER',
    payload: {
        name: 'Bilal',
        competency: ['ASP.NET', 'Angular']
    }
};

The type attribute above describes the intent of the operation. In this case, the type attribute is ADD_DEVELOPER, which means that an operation is being dispatched to add a new Developer object stored in the operation's payload attribute. The payload is just data related to the type of operation that the reducer adds to the new state returned to the Store subscriber.

Reducer or Action Reducer

Action Reducers or Reducers are pure functions as far as state management libraries are concerned. Reducers respond to actions and return a new state object containing all the changes within the state, hence the immutable nature of the state. The reducer analyzes the dispatched action, reads in the action's payload, performs the appropriate action on the state inside the Store, and returns a brand new state object containing all the changes. An example of a Reducer:

 function reducer(state: State, action: Action) {
    const actionType = action.type;
    const developer = action.payload;

    switch (actionType) {
        case 'ADD_DEVELOPER': {
            const developers = [...state.developers, developer];
            return { developers }
        }
        ...
    }
}

During setup of the ngrx/store module, we configure the StoreModule class with the mapping configuration between all available state segments in the application and their corresponding reducers. In other words, this way we tell the Store to use the specified reducer when the Store wants to update a particular state slice.

在这里插入图片描述

The semantics of the above code is to tell Store that when it needs to update the Application State represented by SITE_CONTEXT_FEATURE, please use the reducer pure function represented by reducerToken to do so.


注销
1k 声望1.6k 粉丝

invalid