课程资源: www.ultimatecourse.com
3 principles in Redux
- single source of truth
- One state tree inside store
- predictability, maintainability
- universal apps (SSR)
- testing and debugging
- State is read-only
- Derive properties from state
- Dispatch actions to change the state
- Immutable update patterns
- return a new array, rather than change the current one
- pure functions update state
- pure functions are reducers
- reducers respond to action types
- 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};