This is the 7th day of my participation in the August Text Challenge.More challenges in August

Flux thought

The single flow of data depends on the MVVM pattern

action creator

The man who creates pandas is called Panda Creator

It’s called Dog Creator

For example, the following arrow function is an Action Creator:

() => ({" type ":" ADD "})Copy the code

Summary: Action Creator is a function that returns action

Use Action Creator in the Connect decorator

export default connect(
    ({counterReducer}) = > ({
        v : counterReducer.v
    }),
    {
        add(){
            return {"type" : "ADD"}},minus(){
            return {"type" : "MINUS"}
        }
    }
)(App)
Copy the code

The add () and minus() keys are Action Creators, listing functions that return Action.

Create the counteraction.js file

Expose two Action Creators:

export const add = () = > ({"type" : "ADD"});
export const minus = () = > ({"type" : "MINUS"});
Copy the code

The component simply needs to import the counteraction.js file and modify the connect function

export default connect(
    ({counterReducer}) = > ({
        v : counterReducer.v
    }),
    {
        add,
        minus
    }
)(App)
Copy the code

BindActionCreators is bound to ActionCreator

The invocation needs to use a namespace

import React from 'react';
import { connect } from "react-redux";
import * as counterActions from "./actions/counterActions";
import {bindActionCreators} from "redux";
 
class App extends React.Component{
    constructor(){
        super(a); }render(){
        return(
            <div>
                <h1>{this.props.v}</h1>

                <button onClick={()= >{ this.props.counterActions.add(); I +}} > press</button>

                <button onClick={()= >{ this.props.counterActions.minus(); }} > as I -</button>
            </div>)}}export default connect(
    ({counterReducer}) = > ({
        v : counterReducer.v
    }),
    (dispatch) = > ({
        counterActions: bindActionCreators(counterActions , dispatch)
    })
)(App)
Copy the code

asynchronous

redux-thunk

Thunk stands for formal conversion program

Install dependencies

npm install --save redux-thunk
Copy the code

Once thunk is installed, you can write two parentheses in the action file, as follows

export const addAfter2000ms = () = > () = > {}
export const addAfter2000ms = () = > (dispatch) = > {}
Copy the code

The system comes with dispatch in the second bracket

conclusion
Thunk () => () => {} – thunk () => {}
2) Asynchrony is actually executed in the action file
3) Keep the component files beautiful and tidy
4) No additional IF branch is added in reducer.

Async is used in combination with redux-thunk

import axios from 'axios';
const GETDATA = "GETDATA"
const getData = (url:any, value:any) = > async (dispatch:any) => {
    let results = await axios.post(url, value, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(res= > res.data.data)
    .catch(error= > {
        console.log(error);
    });
    dispatch(fetchData(results));
}
const fetchData = (results:any) = > ({type: GETDATA, results})

export {
    getData
}
Copy the code

redux-saga

Saga means “legend” in English. The idea is interception.

Liverpoolfc.tv: redux-saga.js.org/

The process of Redux-Saga is as follows:

Install dependencies

npm install --save redux-saga
Copy the code

We need to supplement Babel’s plugins. To handle star functions, promises, etc., the babel-plugin-transform-Runtime must be installed.

npm install --save-dev babel-plugin-transform-runtime
Copy the code

Modify webpack.config.js: Find this line: Add a plugin transform-Runtime

plugins: ['transform-object-rest-spread'.'transform-runtime']
Copy the code

Create a saga. Js

export const helloSaga = function* () {
    console.log('I'm Saga, hello! ')}Copy the code

The function has a star, called a generator

Modify main.js entry file reference manual redux-saga.js.org/docs/introd…

Conclusion:
1) Components, action and Reducer files all maintain formal beauty without damaging code tidiness. Actions without two () maintain a high degree of tidiness;
2) Truly implement asynchrony in saga file, while thunk is action file.
3) Saga’s idea is interception. The thunk idea is to “convert the form” by having asynchronous actions write two parentheses. Because Saga has a good mind, it is “pluggable” and feels like managing the entire business logic “externally”, as a separate part.
4) After saga ends, the final product is a PUT, which means forward action.

Promise

Characteristics of the synchronization function

  1. The function must complete all statements before executing subsequent statements
  2. Function body returns a value with return
  3. When the function is called, the left side of the equal sign is received with a variable

Features of asynchronous functions:

  1. The asynchronous function will be followed by the following statement, and when the following statement is cleared (synchronization stack execution completed), asynchronous also completed, execute the callback function;
  2. There is no return inside a function. You must use a callback function to return a value.
  3. When a function is called, you can’t write an equal sign, you can’t use a variable to receive the value, you have to use a callback function to take the value.

Write an asynchronous function, 2000ms return a random number

function getNumberAfter2000ms(cb){
    setTimeout(function(){
        cb(Math.random()); 
    },2000);
}

getNumberAfter2000ms(function(a){
    console.log(a);
});
console.log("Hello");
Copy the code

Callback hell

Call getNumberAfter2000ms 3 times using 6s to get 3 numbers

getNumberAfter2000ms(function(a){
    console.log(a);
    getNumberAfter2000ms(function (b) {
        console.log(b);
        getNumberAfter2000ms(function (c) {
            console.log(c);
        });
    });
});
Copy the code

Know the Promise

  • Promise is a syntactic sugar provided in ES6 that simplifies writing asynchronous functions.
  • Is a built-in constructor provided by ES6

Encapsulate a Promise

Write an asynchronous function that returns a Promise instance with a then method at the center of its circle

The overall structure

function getNumberAfter2000ms(){
    return new Promise(a); } getNumberAfter2000ms().then();Copy the code

When you instantiate a Promise, you must pass in a function (resolve,reject)=>{}. The resolve parameter indicates success, reject parameter indicates failure. Resolve is a callback to success, passed in from then.

function getNumberAfter2000ms(){
    return new Promise((resolve , reject) = > {
        setTimeout(function(){
            resolve(Math.random());
        },2000);
    });
}

getNumberAfter2000ms().then(function(a){
    console.log(a);
});
Copy the code

Now you can chain-call an asynchronous function, and you don’t need to destroy the black hole.

getNumberAfter2000ms()
.then(function(a){
    console.log(a);
    return getNumberAfter2000ms();
})
.then(function (a) {
    console.log(a);
    return getNumberAfter2000ms();
})
.then(function (a) {
    console.log(a);
    return getNumberAfter2000ms();
});
Copy the code

Wrap a promise function of your own

class ChengNuo{
    constructor(fn){
        this.fn = fn;
    }
    then(cb){
        this.fn(cb)
    }
}
function getAfter2s(){
    return new ChengNuo((resolve,reject) = > {
        setTimeout(function(){
            resolve(Math.random())
        },1000)
    })
}
getAfter2s().then(function(b){
    console.log(b);
    return getAfter2s()
})
Copy the code

Fetch () function — poor compatibility

Ask for, get, ask for Inherently returns an instance of Promose

Native FETCH does not use XMLHttpRequest objects, which means fetch is not Ajax.

axios

Functionality: Using the XMLHttpRequest object, emulates the Promise syntax as fetch syntax. Install dependencies:

npm install --save axios
Copy the code

Usage:

import axios from "axios";

function* addServer() {
    const {m} = yield axios.get("/api/shu").then(data= >data.data);
    yield put({ "type": "ADD" , m});
}
Copy the code

async / await

ES7 provides async/await, you can write synchronous functions to call asynchronous functions.

Async can only be added before the function keyword, not before arrow functions.

function getNumberAfter2000ms(){
    return new Promise((resolve , reject) = > {
        setTimeout(function(){
            resolve(Math.random());
        },2000);
    });
}

async function main(){
    const a = await getNumberAfter2000ms().then(data= > data);
    console.log(a);
    const b = await getNumberAfter2000ms().then(data= > data);
    console.log(b);
    const c = await getNumberAfter2000ms().then(data= > data);
    console.log(c);
}

main();
Copy the code

Inside async functions, we can await statements. Await must be followed by the execution of the then method of a function that returns a Promise instance. The then function returns a value that will be automatically received by the variable to the left of the await (this is the c++ browser low-level wrapper).

Await means to wait. It will wait for the asynchronous function to finish executing.

Generator Star function

A Generator is a library interrupt point function that can have multiple return values.

example

function* gen(){
    console.log("Ha ha");
    yield "A";
    console.log("Hee hee");
    yield "B";
    console.log("Moo moo da.");
    yield "C";
}
var I = gen(); // Activate the star function

I.next()     // output ha ha
I.next()     // Output hee hee
I.next()      // Output the output
Copy the code

Yield means “output”, which is the breakpoint of the function.

The gen() function puts the virtual “cursor” in place, on the line below function*. At this point I can call the next() method, which means to execute the function to its nearest yield.

The value after yield can also be seen

console.log(g.next().value); / / output ACopy the code

The star function works perfectly with Promise.

function getNumberAfter2000ms(){
    return new Promise((resolve) = > {
        setTimeout(function(){
            resolve(Math.random())
        },2000);
    });
}

function* gen(){
    yield getNumberAfter2000ms();
    yield getNumberAfter2000ms();
    yield getNumberAfter2000ms();
}

var i = gen();  // Activate and prepare the cursor

i.next().value
.then(data= >{
    console.log(data);
    return i.next().value;
})
.then(data= > {
    console.log(data);
    return i.next().value;
})
.then(data= > {
    console.log(data);
})
Copy the code

Encapsulate a delay function

function delay(time){
    return new Promise((resolve) = >{
        setTimeout(function(){
            resolve()
        },time)
    })
}

function* gen(){
    yield delay(2000)
    yield Math.random()
}
Copy the code

Thank you

Thank you in your busy schedule to open this article, I hope to help you, if you have any questions, welcome to point out.

If you think it’s okay, give it a thumbs up.