All application state are stored in a single target in the form of a tree store in. The only way is to change the state trigger Action , a description of what happens. In order to describe how action to change the state tree, you need to write reducers.
Redux and store only a single stage of a root reduce function (reducers). With the increasing application should be split at the root level of the reducers reducer into a plurality of small, independent operation of the different parts of each state tree, rather than adding new stores.
Three principles
A single data source
State the entire application is stored in an object tree, and only exists in the object tree in only one store . State from the server may be serialized and injected into the client without having to write additional code.
State is read-only
The only way is to change the state of the starting action, action is a general object description for events that have occurred . This ensures that the view and network requests can not directly modify the state, instead they can only express intention want to modify.
The use of pure function to perform the modification
In order to describe how action to change the state tree, you need to write reducers . Reducer just some pure function that takes the previous state and action, and returns the new state.
basis
Action
Action payload to store the data transmitted from the application. It is the only source of state data. Usually by store.dispatch()
the action reached the store. Action is the essence JavaScript ordinary objects. There must be a string type of the action type
field to indicate the action to be performed. In most cases type
it will be defined as string constants. When the large-scale application may be used alone module or file storage action.
We also need to add a action index
field to indicate the serial number of a user action to complete the task. Because the data is stored in an array, so we pass subscript index
hey refer to a specific task. The reference to the actual project in general will generate a unique ID as the data in the new data when identity.
{
type: TOGGLE_TODO,
index:5
}
We should minimize data transfer in the action . Transfer index
than pass the entire task objects better.
Action to create functions
Action to create a function that is a method of generating action. Redux action in the creation function simply returns an action:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
This is action to create functions easier porting and testing. In traditional Flux, the action created when calling the function, usually triggers a dispatch:
function addTodoWithDispatch(text) {
const action = {
type: ADD_TODO,
text
}
dispatch(action)
}
Redux result in action just need to create a function passed to the dispatch()
method to trigger a dispatch process:
dispatch(addTodo(text))
dispatch(completeTodo(index))
Or create a bound action to automatically dispatch:
const boundAddTodo = text => dispatch(addTodo(text))
const boundCompleteTodo = index => dispatch(completeTodo(index))
store in direct by store.dispatch()
calling dispatch()
methods, but in most cases we will use the react-redux provided connect()
helper to call. BindActionCreators()
More action can automatically create a function to bind to dispatch()
the method.
Reducer
Reducers how to specify the application state changes in response actions and sent to the store, actions have just described the fact that things happen, and does not describe how to update the application state.
In Redux applications, all of the state are kept in a single object, before writing the code should first think about the structure of the object. How can the most simple form of the state with the target applications describe.
To todo application, for example, need to save two different data:
-
The currently selected task filter conditions;
-
A complete list of tasks.
The state tree is usually required to store other data, as well as some UI related state. Try to separate these data state associated with the UI.
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'keep all state in a single tree',
completed: false
}
]
}
Action processing
Determined the structure of state object, we can begin to develop reducer. reducer is a pure function that takes the old state and action, return the new state.
(previousState, action) => newState
Reducer is very important to keep clean, so never do these things in the reducer:
-
Modify the parameters passed;
-
Performing an operation side effects;
-
Call impure functions.
As long as the same pass parameters, return the next state calculated to be the same. No special circumstances, no side effects, no API request, without modifying variables, simple calculation is performed.
Store
Use action to describe "what happened", using reducer to update the state of action based on usage. Store is to the object they link together. Store has the following duties:
-
Maintaining the state of the application;
-
Provide
getState()
methods to obtain state; -
Provide
dispatch()
methods to update state; -
By
subscribe(listener)
registering a listener; -
By
subscribe(listener)
cancellation listener function returns.
Redux use only a single Store . When the need to split the data logic, should be used in combination instead of creating a plurality of reducer store.
data flow
Strict way data flow is the core design Redux structure.
This means that all application data follow the same statement cycle, which would allow applications become more predictable and agreed understanding. While also encouraging for data standardization, avoid the use of multiple, independent of each other and can not be referenced duplicate data.
Application lifecycle of data Redux follow four steps:
1 call store.dispatch(action)
.
2, Redux store incoming calls reducer function.
3, a plurality of sub-root reducer reducer output should be combined into a single state tree.
4, Redux store to save a complete state tree root reducer returned.
With React
Redux support React, Angular, Ember, JQuery or even pure JavaScript. React form but allows the function to describe the interface state, Redux to initiate action in the form of state changes.
Installation React-Redux:
npm install --save react-redux
Redux is based on the React Bindery container components and display components separated from the development of ideas, this idea is very important.
Display assembly | The container assembly | |
---|---|---|
effect | It describes how to show (skeleton, style) | Describe how to run (data acquisition, status updates) |
Direct use Redux | no | Yes |
Data Sources | props | Listening Redux state |
Data Modification | Callback function from props | To distribute actions Redux |
Called | Manually | Typically generated by React Redux |
Most of the components should be showing type, but generally require a handful of container components and Redux store them connected.
For example, we want to display a list of todo items. After a todo item is clicked, will add a strikethrough and marked as completed. We will show the user to add a todo field. A switchable display all / display only the completed / todos incompleted only display in the footer.
Display components and their props:
-
TodoList
Todos is used to display the list.-
todos: Array
To{ text, completed }
todo items displayed in the form of an array. -
onTodoClick(index: number)
When the callback function called todo item is clicked.
-
-
Todo
A todo item.-
text: string
Displayed text. -
completed: boolean
todo item is displayed with strikethrough. -
onClick()
When the callback function called todo item is clicked.
-
-
Link
Links with callback callback function.-
onClick()
When you click the link triggers.
-
-
Footer
It allows the user to change the visibility todo a filter assembly. -
App
Root component, rendering all the rest of the content.
These components define the appearance of not only concerned with data sources and how to change. What passed on what rendering. If the code migration from Redux to another structure. These components can be used directly without any changes.
Container components:
Also we need some container assembly to the display assembly connected to Redux. For example, display type, TodoList
assembly requires a similar VisibleTodoList
container store to monitor and process variations Redux how filtered data to be displayed. In order to achieve the state of the filter, the need to achieve FilterLink
a container assembly is to render Link
and trigger a corresponding action when clicked:
-
VisibleTodoList
Todo list to filter the currently displayed depending on the state, and renderingTodoList
. -
FilterLink
Get the current filter and renderingLink
.-
filter: string
It is the current filtering state.
-
Other components:
Sometimes severe form and function coupled together, it is difficult to distinguish between the use of container components or display components:
-
AddTodo
Input box containing the "Add" button.