1 Redux understand

1.1 Learning Documents

  1. English document: redux.js.org/

  2. Chinese document: www.redux.org.cn/

  3. Making: github.com/reactjs/red…

1.2 What is Redux

  1. Redux is a JS library for state management (not the React plugin library)
  2. It works with React, Angular, vue, etc., but mostly works with React
  3. Function: Centrally manages the state shared by multiple components in the React application

1.3 When should Redux be used

  1. The state of a component that needs to be readily available to other components (shared)
  2. One component needs to change the state of another component (communication)
  3. General principle: don’t use it if you can, and only consider using it if you don’t have to work hard

1.4 Redux workflow

Note: Redux is only responsible for managing status. it’s up to us to write the state changes that drive the display of the page

The three core concepts of Redux

2.1 the Action

  1. Object of action

  2. Contains two properties

    • Type: Identifies the attribute. The value is a string, unique, required attribute
    • Data: Data attribute. The value type is arbitrary and optional
  3. Example:

    {
    	type:'ADD STUDENT'.data: {name:'Tom'.age:18}}Copy the code

2.2 Reducer

  1. Used for initialization state, machining state

  2. During processing, pure functions of the new state are generated based on the old state and action

  3. Description:

    1) Reducer is essentially a function that receives prestate and action and returns the state after processing

    2) Two roles of Reducer: initialization state and machining state

    3) The reducer was automatically triggered by the store for the first call, the preState was undefined and the action was {type:’ @@redux /INIT_a.2.b.4}

2.3 Store

  1. The object that links state, Action, and Reducer together

  2. How do I get this object

    (1)

    import {createStroe} from 'redux'
    Copy the code

    (2)

    import reducer from './reducers'
    Copy the code

    (3)

    const stroe = createStore(reducer)
    Copy the code
  3. The functionality of this object

    (1) getState() : getState

    (2) Dispatch (action) : Distribute actions, trigger the reducer call, and generate a new state

    (3) Subscribe (listener) : Register to listen, automatically call when a new state is generated

  4. Code:

    1) Introduce the createStore function in Redux to create a store

    2) A Reducer that serves the createStore call is passed in

    3) Remember to expose the Store object

Redux’s core API

3.1 createstore ()

Create a store object that contains the specified reducer

3.2 store object

  1. Role: The redux library is the core managed object

  2. It maintains internally:

    1) the state

    2) reducer

  3. Core approach:

    1) getState() : get the state

    2) Dispatch (Action) : Dispatch action

    3) Subscribe (listener) : Monitor state changes in REdux, such as redux state changes, then re-render App components

    Note: There is no need to detect redux state changes after using React-redux. The container component does this automatically

  4. Specific coding

    1) store. GetState ()

    2) store. Dispatch ({type: INCREMENT, nubmer})

    3) This is done automatically in React-redux

    // Put it in index.js
    store.subscribe(() = > {
        ReactDOM.render(<App/>.document.getElementById('root'))})Copy the code

3.3 applyMiddleware ()

What it does: Redux-based middleware (plug-in library) on applications

Middleware is most commonly used for asynchronous Actions without having to reference a lot of code or rely on third-party libraries like Rx. This allows you to dispatch asynchronous actions just like you dispatch normal Actions.

import {createStore,applyMiddleware} from 'redux';
// Redux-thunk is introduced to support asynchronous action
import thunk from 'redux-thunk';
/ / introduce redux devtools -- the extension
import {composeWithDevTools} from 'redux-devtools-extension'
//暴露store
export default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)))
Copy the code

3.4 combineReducer ()

Function: Combine multiple Reducer functions

// Introduce the combineReducer to integrate multiple reducer
import {combineReducers} from 'redux';
// Import the reducer as the Count component service
import count from './count';
// Import the Reducer as the Person component service
import persons from './person';


// Summarize all the reducer into a total reducer
export default  combineReducers({
    count,
    persons
})
Copy the code

4 Redux asynchronous programming

4.1 understand

  1. Redux cannot be processed asynchronously by default,

  2. Sometimes applications need to perform asynchronous tasks in ==redux ==(Ajax, timer)

// Async action, return function, async action usually call synchronous action, async action is not necessary
export const incrementAsync = (data,time) = > {
    return (dispatch) = > {
        setTimeout(() = >{ dispatch(increment(data)) }, time); }}Copy the code

4.2 illustrates

  1. When to use: Deferred actions do not want to be assigned to the component itself, they want to be assigned to the action

  2. When asynchronous action is needed: You want to operate on the state, but the specific data is returned by the asynchronous task

  3. Specific code:

    1) YARN add redux-thunk and configure it in store

    export default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)))
    Copy the code

    2) The function that creates the action no longer returns a generic object, but a function that writes asynchronous tasks.

    3) After the asynchronous task results, distribute a synchronous action to actually manipulate the data.

  4. Note: Asynchronous actions are not mandatory. You can wait for the results of asynchronous tasks before distributing synchronous actions.

5 react-redux

5.1 understand

  1. React plugin library
  2. Redux is designed to simplify the use of react applications
  3. Note: Redux is not specifically used for React, nor is it made by Facebook. React-redux is made by Facebook

The principle diagram of the 5.2

5.2 React-Redux components fall into two categories

  1. UI components

    1) Only responsible for the presentation of the UI without any business logic

    2) Receiving data (general data and functions) via props

    3) Do not use any API in Redux

    4) Generally stored in the Component folder

  2. Container components

    1) Responsible for data and business logic, not UI presentation, responsible for communicating with Redux and handing the results to UI components

    2) Use Redux’s API

    3) Generally, it is stored in the Container folder

  3. What steps does a component go through to interact with Redux?

    1) Define UI components — not exposed

    2) Introduce connect generation to the container component and expose it as follows

    connect(state= >({key:value}),// Mapping state
            {key:xxxAction}  // A method to map operation state) (UI components)Copy the code

    3) Read and manipulate the state in the UI component via this.props. XXX

5.3 the relevant API

  1. Provider: Lets all components get state data

        <Provider store={store}>
            <App/>
        </Provider>,document.getElementById('root'))
    
    Copy the code
  2. Connect: Used to wrap UI components to generate container components

    import { connect } from 'react-redux'
      connect(
        mapStateToprops,// Mapping state, return value is an object
        mapDispatchToProps// a method that maps the operation state. The return value is an object
      )(Counter)
    Copy the code
  3. MapStateToprops: Converts external data (that is, state objects) to the tag component of the UI component

    1) The mapStateToProps function returns an object

    2) Return the key as the key passed to the PROPS of the UI component, and the value as the value passed to the props of the UI component

    3) mapStateToProps is used to pass state

    const mapStateToprops = function (state) {
      return {
        value: state
      }
    }
    Copy the code
  4. MapDispatchToProps: Converts the function that distributes actions to the tag properties of the UI component

    1) mapDispatchToProps returns an object

    2) Return the key as the key passed to the PROPS of the UI component, and the value as the value passed to the props of the UI component

    3) mapDispatchToProps method for passing operation objects

    Note: mapDispatchToProps can also be an object

  5. CombindeReducers: Used to merge multiple reducer, so that it can share data, the total state after merging is an object!!

    // Introduce the combineReducer to integrate multiple reducer
    import {combineReducers} from 'redux';
    // Import the reducer as the Count component service
    import count from './count';
    // Import the Reducer as the Person component service
    import persons from './person';
    // Summarize all the reducer into a total reducer
    export default  combineReducers({
        count,
        persons
    })
    
    Copy the code

    Note: The reducer is delivered to the store. Finally, note that when removing the state from the component, remember to “take the state in place” and specify which state (state.xxx).

6 Redux debugging tool

  1. Install the Chrome plug-in

  2. Download the tool dependency package

npm install --save-dev redux-devtools-extension
Copy the code
  1. Store
import {composeWithDevTools} from 'redux-devtools-extension'
					const store = createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))
Copy the code

Pure functions and higher-order functions

7.1 pure functions

  1. A special class of functions that give the same input (argument) and return the same output (return)

  2. The following constraints must be observed

    1) Parameter data shall not be overwritten

    2) There will be no side effects, such as network requests, input and output devices

    3) You cannot call date.now (), or math.random (), or other impure methods

  3. The Reducer function of redux must be a function

7.2 Higher-order functions

  1. Understanding: a special class of functions

    1) Case 1: Arguments are functions

    2) Case 2: Return is a function

  2. Common higher-order functions:

    1) Timer setting function

    ForEach ()/ map()/ filter()/ reduce()/ find()/ bind()

    3) promise

    4) Connect function in reactr-reduc

  3. Function: Can realize more dynamic, more extensible function

8 reference

Still Silicon Valley React family barrel

9 code

Making the address