Redux Learning Series (1) - Introduction to Basic Concepts

Introduction

ReduxIt is a predictable JavaScriptapplication state management container, which can also be said to be an application data flow framework.

effect

ReduxIt 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 Reactthe component tree, which is equivalent to Reacta stateful modeling of the component tree:
insert image description here

  1. Redux can ignore the component hierarchy;
  2. For component systems, redux is a third-party, global "variable".

characteristic

  • Predictable
    ReduxIt 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 DevToolsMake it easy to track when, where, and how the state of your application changes.
  • The clear structure of the data flow
    Reduxcan record every change, and with the help of "time travel debugging", it can even send a complete error report to the server.
  • Flexible
    ReduxCan be used with any UIlayer framework, and has a huge plugin ecosystem.

learning documents

Redux Chinese official website

advantage

Using in your application Reduxhas the following benefits:

  1. Prediction
    always has an accurate source of data, that is store, there is no confusion about how to synchronize actionsand other parts of the application with the current state.
  2. Maintenance
    The nature of predictable results and strict organizational structure make the code easier to maintain.
  3. Organization
    Be stricter about how code should be organized, which makes code more consistent and easier for teams to collaborate on.
  4. Testing
    The first rule of thumb for writing testable code is to write small, self-contained functions that do only one thing. ReduxAlmost all of the code in is such a function: short, pure, and separated.
  5. Server-side rendering
    can lead to a better user experience and help with SEO, especially for first renders. Just storepass to the client.
  6. Developer Tools
    Developers can track everything that is happening in the application in real time, from actionschanges to state.
  7. Community and Ecosystem
    There are many Reduxsupporting communities that make it more attractive to use.

Core idea

ReduxThere are three core concepts: action、store、reducer.

insert image description here

store

ReduxInside , Storeis a warehouse that integrates actionand reducerused to save the data that needs to be managed by the entire application state. ( similar in sensevuex to )store

ReduxProvides a createStoreto create state. as follows:

import {
    
     createStore } from 'redux';
// 创建 store
let store = createStore(rootReducer);
let authInfo = {
    
    username: 'admin', password: '123'};
store.dispatch(authUser(authInfo));

createStoreA function that takes another function as an argument and returns a newly generated Storeobject .

storefeatures

  1. one and only onestore
  2. Maintain the state of the application and get the state:store.getState()
  3. storeReceived as an argument when creating a reducer:const store = createStore(reducer)
  4. When a status update is initiated, it needs to distributeaction:store.dispatch(action)

store.getState()

store.getState(): Get the value stored storein

store.dispatch(action)

store.dispatch(action): dispatch action, the parameter is an action object{ type: 'xxx', data: xxx }

store.subscribe()

store.subscribe(): StoreIt is allowed to use store.subscribethe method to set the monitoring function to monitor storethe change of the value, and Stateonce the value changes, this function will be executed automatically.

Listen storefor :

// redux只维护状态,但是不会触发页面更新(不会触发组件render的调用)
// 检测redux中状态的变化,就调用render
store.subscribe(() => {
    
    
    this.setState({
    
    }); // 传入空对象,只为触发组件的render方法
});

If each component needs to be monitored store, it can be monitored in index.jsthe entry file store, and appthe component .

Due to reactthe diffalgorithm, 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.subscribeThe method returns a function that can be called to remove the listener.

as follows:

let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);

unsubscribe();

actions

ActionsIt is an event, passing an operation initiated from the view layer of this application (such as user interface, internal events such as APIcall and form submission), telling storeneeds to change state.

ActionsSubmit data to storeand storeonly get information Actionsfrom .

ActionDescribes the type actionof and storethe payload information passed to , it has two properties:

(1) type(usually a constant): identifies the attribute, indicating the name actionof the ;

(2) payload: data attribute, optional. It can take some parameters to indicate the data carried by this action, which is used as Storea change .

as follows:

{
    
    
    type: LOGIN_FORM_SUBMIT,
    payload: {
    
    username: 'admin', password: '123'}
}

As shown above, a LOGIN_FORM_SUBMITnamed Action, which also carries payloadthe parameter.

Action Creator

ViewThere will be as many kinds of messages as there are to be sent Action. In Redux, you can use Action Creatorthe generator to batch generate some Action:

function authUser(form) {
    
    
    return {
    
    
        type: LOGIN_FORM_SUBMIT,
        payload: form 
    }
}

store.dispatch()

ActionThe change operation will not be issued by itself Store. It needs to be called in the application using dispatchthe method actions, which is specially used to issue action:

dispatch(authUser(form));

ReduxInside , isstore.dispatch() the only way that emits .ViewAction

actionfeatures

  1. only describe what to do;
  2. JSObject, must have typeattribute , used to distinguish the type of action;
  3. Depending on the function, additional data can be carried to cooperate with the data to complete the corresponding function.

reducers

When a is store.dispatchinitiated actionby a , it arrives reducer, reducergets the current state and events of the application and completes, computes, and returns a new statestate object to store(this makes Reduxvery simple and predictable).

JavaScriptIn functional reducerbased array reducemethods , 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 Reduxprovided combineReducers()examples. It combines all the s in this application reducerinto a single index reducer. Each is reducerresponsible for the state of its own part of the application, and this state parameter is different from the reducerothers . 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, Reduxa 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 added Immutable.js.

reducerfeatures

  1. is a pure function that looks at the previous state, executes a actionand returns a new state;
  2. Takes two arguments: the current stateand the received action, and returns a new one state.

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.

Guess you like

Origin blog.csdn.net/HH18700418030/article/details/130325221