Introduction
Redux
It is a predictable JavaScript
application state management container, which can also be said to be an application data flow framework.
effect
Redux
It is mainly used for application state management. It extracts the state of all components and constructs a centralized single constant state tree (object) to save the state of the entire application. This state tree is in one-to-one correspondence with React
the component tree, which is equivalent to React
a stateful modeling of the component tree:
- Redux can ignore the component hierarchy;
- For component systems, redux is a third-party, global "variable".
characteristic
- Predictable
Redux
It is possible to develop applications with stable and predictable behavior, which can run in different environments (client, server and native programs), and are easy to test. - Centralized management
Centralized storage and management of the state of the application can develop powerful functions, such as undo/redo, state persistence, and so on. - Debuggable
Redux DevTools
Make it easy to track when, where, and how the state of your application changes. - The clear structure of the data flow
Redux
can record every change, and with the help of "time travel debugging", it can even send a complete error report to the server. - Flexible
Redux
Can be used with anyUI
layer framework, and has a huge plugin ecosystem.
learning documents
Redux Chinese official website
advantage
Using in your application Redux
has the following benefits:
- Prediction
always has an accurate source of data, that isstore
, there is no confusion about how to synchronizeactions
and other parts of the application with the current state. - Maintenance
The nature of predictable results and strict organizational structure make the code easier to maintain. - Organization
Be stricter about how code should be organized, which makes code more consistent and easier for teams to collaborate on. - Testing
The first rule of thumb for writing testable code is to write small, self-contained functions that do only one thing.Redux
Almost all of the code in is such a function: short, pure, and separated. - Server-side rendering
can lead to a better user experience and help with SEO, especially for first renders. Juststore
pass to the client. - Developer Tools
Developers can track everything that is happening in the application in real time, fromactions
changes to state. - Community and Ecosystem
There are manyRedux
supporting communities that make it more attractive to use.
Core idea
Redux
There are three core concepts: action、store、reducer
.
store
Redux
Inside , Store
is a warehouse that integrates action
and reducer
used to save the data that needs to be managed by the entire application state
. ( similar in sensevuex
to )store
Redux
Provides a createStore
to create state
. as follows:
import {
createStore } from 'redux';
// 创建 store
let store = createStore(rootReducer);
let authInfo = {
username: 'admin', password: '123'};
store.dispatch(authUser(authInfo));
createStore
A function that takes another function as an argument and returns a newly generated Store
object .
store
features
- one and only one
store
- Maintain the state of the application and get the state:
store.getState()
store
Received as an argument when creating areducer
:const store = createStore(reducer)
- When a status update is initiated, it needs to distribute
action:store.dispatch(action)
store.getState()
store.getState()
: Get the value stored store
in
store.dispatch(action)
store.dispatch(action)
: dispatch action, the parameter is an action object{ type: 'xxx', data: xxx }
store.subscribe()
store.subscribe()
: Store
It is allowed to use store.subscribe
the method to set the monitoring function to monitor store
the change of the value, and State
once the value changes, this function will be executed automatically.
Listen store
for :
// redux只维护状态,但是不会触发页面更新(不会触发组件render的调用)
// 检测redux中状态的变化,就调用render
store.subscribe(() => {
this.setState({
}); // 传入空对象,只为触发组件的render方法
});
If each component needs to be monitored store
, it can be monitored in index.js
the entry file store
, and app
the component .
Due to
react
thediff
algorithm, if there is no change in the components, all components will not be updated, and the page will not be redrawn and rearranged, so there is no need to worry about efficiency.
unlisten
store.subscribe
The method returns a function that can be called to remove the listener.
as follows:
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
);
unsubscribe();
actions
Actions
It is an event, passing an operation initiated from the view layer of this application (such as user interface, internal events such as API
call and form submission), telling store
needs to change state
.
Actions
Submit data to store
and store
only get information Actions
from .
Action
Describes the type action
of and store
the payload information passed to , it has two properties:
(1) type
(usually a constant): identifies the attribute, indicating the name action
of the ;
(2) payload
: data attribute, optional. It can take some parameters to indicate the data carried by this action, which is used as Store
a change .
as follows:
{
type: LOGIN_FORM_SUBMIT,
payload: {
username: 'admin', password: '123'}
}
As shown above, a LOGIN_FORM_SUBMIT
named Action
, which also carries payload
the parameter.
Action Creator
View
There will be as many kinds of messages as there are to be sent Action
. In Redux
, you can use Action Creator
the generator to batch generate some Action
:
function authUser(form) {
return {
type: LOGIN_FORM_SUBMIT,
payload: form
}
}
store.dispatch()
Action
The change operation will not be issued by itself Store
. It needs to be called in the application using dispatch
the method actions
, which is specially used to issue action
:
dispatch(authUser(form));
Redux
Inside , isstore.dispatch()
the only way that emits .View
Action
action
features
- only describe what to do;
JS
Object, must havetype
attribute , used to distinguish the type of action;- Depending on the function, additional data can be carried to cooperate with the data to complete the corresponding function.
reducers
When a is store.dispatch
initiated action
by a , it arrives reducer
, reducer
gets the current state and events of the application and completes, computes, and returns a new state
state object to store
(this makes Redux
very simple and predictable).
JavaScript
In functionalreducer
based arrayreduce
methods , receiving a callback (reducer
) can get a single value from multiple values, a sum of integers, or an accumulation of a series of values.
as follows:
function handleAuth(state, action) {
return _.assign({
}, state, {
auth: action.payload
});
}
For more complex projects, it is recommended to use the
Redux
providedcombineReducers()
examples. It combines all the s in this applicationreducer
into a single indexreducer
. Each isreducer
responsible for the state of its own part of the application, and this state parameter is different from thereducer
others .combineReducers()
Instances make the file structure easier to maintain.
as follows:
const rootReducer = combineReducers({
handleAuth: handleAuth,
editProfile: editProfile,
changePassword: changePassword
});
If an object changes
(state)
only some values,Redux
a new object is created, those values that have not changed will point to the old object and new values will be created. This is great for performance. To make it more efficient can be addedImmutable.js
.
reducer
features
- is a pure function that looks at the previous state, executes a
action
and returns a new state; - Takes two arguments: the current
state
and the receivedaction
, and returns a new onestate
.
A pure function means that for the same input, there will only be the same output, and it will not affect or be affected by external values.