How Redux works
Redux manages global state through store;
The view generates an action and sends it to the store via dispatch(action).
The store will send the current state and this action to the Reducer. After the reducer process, a new state needs to be returned. At this time, the Store can know the data changes and then return to the notification view to obtain the latest data.
Basic concepts and apis
Store
A Store is an object that maintains all of the state tree of an application.
The only way to change state in a store is to dispatch an action on it.
There can only be one Store for the entire app.
Store method
Provide the getState() method to getState; Provide a dispatch(action) method to update state; Register a listener with subscribe(listener); Unsubscribe the listener via a function returned by subscribe(listener).Copy the code
Reducer
Reducer is a pure function.
It takes two arguments, the first being the state to be managed, and the second being the action.
Reducer will perform different operations on the state based on the type value of the incoming action and return a new state instead of modifying the original state. However, if there is an unknown (mismatched) action, the reducer will return the original state without any changes.
const reducer =(state,action)=>{
switch(action.type){
case ADD_TODO:
return newstate;
default return state
}
}
Copy the code
Action
An action is essentially an object;
It is the only source of store data. It will ship data to the Store.
Const action={type:'ADD_TODO', payload:'redux principle '}Copy the code
Three principles of application
When we use Redux, we need to follow these three principles to avoid 90% of the bugs:
- Single data source
We treat Store as a global object that is unique and all states are ‘uniformly configured’ in the Store state tree.
- State is read-only
If you want to change the State, you must pass the Action, and the reducer is the specific reducer that makes the update on the State take effect.
This ensures that neither views nor network requests can directly modify state, instead they can only express the intent to change it.
- Reducer must be a pure function
The execution operations within Reducer must have no side effects and state cannot be directly modified. When the state changes, a new object needs to be returned to represent the new state.
This ensures that the same State must get the same View.
What needs to be observed is:
An API that cannot overwrite arguments and cannot call system I/O cannot call impure methods such as date.now () or math.random () because it will get different results each timeCopy the code