Write in front
This series is my synchronous notes when learning redux. The learning materials are:Redux Chinese document。
motivation
Background: single page application,JS needs to manage many states。
Two concepts: change and asynchrony
Combination of react and react: react prohibits asynchrony and directly operates DOM in the view layer, and Redux processes the data in state.
Purpose:Redux tries to make state changes predictable。
Three principles
Single data source
Pay attention to understanding:The state of the entire application is stored in an object tree, and the object tree exists in only one store.
State is read-only
The only way to change state is to trigger action, which is a common object used to describe events that have occurred.
store.dispatch({
type: 'ADD_ Item ', // specify the required type attribute in an action object
index: 1
});
Use pure functions to perform modifications
To describe how an action changes a state tree, you need to writereducers。
What are reducers?
Pure function, such as: (state, action) = > State
As the application becomes larger, pay attention to splitting a large reducer into multiple small reducers to operate different parts of the state tree independently.
//reducer 1
function visibilityFilter(state = 'SHOW_ALL', action){
switch (action.type){
case 'SET_VISIBILITY_FILTER':
return action.filter;
Default: // must exist! Otherwise, undefined will be returned
return state;
}
}
//reducer 2
function todos(action = [], action){
switch (action.type){
case 'ADD_TODO':
return [
... State, // ES6 great method!
{
text: action.text,
complete: false
}
];
case 'COMPLETE_TODO':
return state.map((todo, index) => {
if (index == action.index){
return Object.assign({}, todo, {
complete: true
});
}
return todo;
});
default:
return state;
}
}
import { combineReducers, createStore } from 'redux';
let reducer = combineReducers({ visbilityFilter, todos });
let store = createStore(reducer);