Ngrx 笔记


课程资源: www.ultimatecourse.com

3 principles in Redux

  1. single source of truth
    1. One state tree inside store
    2. predictability, maintainability
    3. universal apps (SSR)
    4. testing and debugging
  2. State is read-only
    1. Derive properties from state
    2. Dispatch actions to change the state
    3. Immutable update patterns
      1. return a new array, rather than change the current one
  3. pure functions update state
    1. pure functions are reducers
    2. reducers respond to action types
    3. reducers return new state

Core concepts

single state tree

  • plain javascript object
  • composed by reducers
const state = {
  todos: [],
};

actions

  • two properties
    • type: string, describes event
    • payload: optional data
  • dispatch actions to reducers
const action = {
  type: 'ADD_TODO',
  payload: {
    label: 'Eat pizza',
    complete: false,
  }
};

reducers

  • pure functions
  • Given dispatched action
    • Responds to action.type
    • access to action.payload
    • composes new state
    • return new state
function reducer(state, action) {
  switch(action.type) {
    case 'ADD_TODO': {
      const todo = action.payload;
      const todos = [...state.todos, todo];
      return {todos};
    }
  }
 return state;
}

store

  • state container
  • components interact with the store
    • subscribe to slices of state
    • dispatch actions to the store
  • store invokes reducers with previous state and action
  • reducers compose new state
  • store is updated, notifies subscribers

one-way dataflow

component -> action -> reducer -> store -> selector ->component

Understanding Immutability

  • predictability
  • explicit state changes
  • performance (change detection)
  • mutation tracking
  • undo state changes

Mutability in JavaScript

Function, array, object

Immutability in JavaScript

Number, String

const name = ['a','b'];
const newName = [...name, 'c'];

const person {'name': 'bob'};
const newPerson = {...person, 'age': 25};

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.