preface

Redux must be used by many students, but redux source code is what it looks like, it is not difficult, how to start to achieve it? I heard that Redux has 100 lines of code, but 10,000 lines of comments, etc. Today we unveil the mystery of Redux

What does Redux do?

In a nutshell: Redux is for state management

Why redux?

In a nutshell: As projects get bigger, it gets harder to pass data between components

What are the core apis of Redux

const store = Redux.createStore(reducer, initialState);
function reducer(state, action){};
store.getState();
store.subscribe(function(){});
store.dispatch({type:'description'});
Copy the code

Write a story

As you can see from the API above, Redux has a createStore method that returns a store object, which has three methods

// Create store, return three methods
function createStore(reducer) {
    // Get all states
    function getState() {}
    // Execute the subscription method
    function subscribe() {}
    // Trigger a state change
    function dispatch() {}
    return {
        getState,
        subscribe,
        dispatch,
    };
}
Copy the code

We create an index.html, create two buttons, a +1 button and a -1 button, and display state in span

<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
</head>
<body>
    <button id="increment">+ 1</button>
    <span id="state">0</span>
    <button id="decrement">- 1</button>
</body>
<script src="./myRedux.js"></script>
</html>
Copy the code

And then look at the browser, very simple design style

And then we introduce our Redux

<script src="./MyRedux.js"></script>
Copy the code

Reducer (state = initialState, action){}; Then write our reducer

Note:

  • Reducer must be a pure function
    • Do not modify the parameters passed in
    • Impure functions such as date.now () must not be called
    • Do not perform side effects, such as API requests and route jumps
  • Return a new state
  • You have to say default

So our reducer came on the scene, ✨✨✨

function reducer(state, action) {
    switch (action.type) {
        case "increment":
        return state + 1;
        case "decrement":
        return state - 1;
        default:
        returnstate; }}Copy the code

Start by creating a store using our createStore method

const store = createStore();
Copy the code

If you look at the console, it prints out our three methods that have nothing, as we expected

We then pass our Reducer to the createStore brother and add the initial values

<script src="./MyRedux1.js"></script>
<script>
function reducer(state, action) {
    switch (action.type) {
        case "increment":
        return state + 1;
        case "decrement":
        return state - 1;
        default:
        returnstate; }}const store = createStore(reducer, 0);
</script>
Copy the code

The reducer and reducer methods are accepted in createStore. State is a state that should not disappear after the createStore method is implemented

// Create store, return three methods
function createStore(reducer, initialState) {
    // Closures store state
    let state = initialState;
    // Get all states
    function getState() {
        return state;
    }
    // Execute the subscription method
    function subscribe() {}
    // Trigger a state change
    function dispatch(action) {}
    return {
        getState,
        subscribe,
        dispatch,
    };
}
Copy the code

Now let’s click on the button to change the state value with dispatch and let’s pull out our intensive and look at the triggering process to connect the dots

The dispatch method is also easy to write

Function dispatch(action) {// New state state = reducer(state, action); }Copy the code

Is the feeling very simple, ha ha 😝

So let’s write click events

const incrementBtn = document.getElementById("increment");
const decrementBtn = document.getElementById("decrement");
incrementBtn.onclick = function () {
 store.dispatch({ type: "increment" });
};
decrementBtn.onclick = function () {
 store.dispatch({ type: "decrement" });
};
Copy the code

The next step is to change the value of the SPAN node

const state = document.getElementById("state");
incrementBtn.onclick = function () {
store.dispatch({ type: "increment" });
state.innerHTML = store.getState();
};

decrementBtn.onclick = function () {
store.dispatch({ type: "decrement" });
state.innerHTML = store.getState();
};
Copy the code

And then we realize that our short version of Redux is implemented, and we have a subscribe method that is not implemented, so what does the subscribe method do

Subscribe is just a function that listens every time the state changes, which is essentially a publish subscribe, so let’s implement that

function createStore(reducer,initialState){
    // Initialize the subscriber array
    const listener = [];
    // Execute the subscription method
    function subscribe(func) {
      // Store subscriber functions
     listener.push(func);
    }
    // Trigger a state change

    function dispatch(action) {
        state = reducer(state, action);
        for (let i = 0; i < listeners.length; i++) {
            const listener = listeners[i];
            / / executionlistener(); }}}Copy the code

Once written, we can use it in our index. HTML

<body>
    <button id="increment">+ 1</button>
    <span id="state">0</span>
    <button id="decrement">- 1</button>
</body>
<script src="./MyRedux1.js"></script>
<script>
    function reducer(state, action) {
        switch (action.type) {
            case "increment":
                return state + 1;
            case "decrement":
                return state - 1;
            default:
                returnstate; }}const store = createStore(reducer, 0);
    const incrementBtn = document.getElementById("increment");
    const decrementBtn = document.getElementById("decrement");
    const state = document.getElementById("state");
    incrementBtn.onclick = function () {
        store.dispatch({ type: "increment" });
    };
    decrementBtn.onclick = function () {
        store.dispatch({ type: "decrement" });
    };
    store.subscribe(function () {
         state.innerHTML = store.getState();
    });
</script>
Copy the code

Conclusion:

Brief version of Redux we will first achieve here, behind we will go deep, this is only the first article, the source can look at github, github.com/Y-wson/Dail…

I hope that my article is helpful to you, to help you improve, as soon as possible to god great perfection, 😝