Overview of Redux Basics

What is Redux?

A library focused on state management, decoupled from react, single state, one-way data flow

Core concepts: store, state, action, reducer

For Redux, there are only these three elements:
a. Action is a purely declarative data structure that only provides all the elements of an event and does not provide logic.
b. The reducer is a matching function, and the sending of actions is global: all reducers can capture and match whether they are relevant or not. If relevant, take away the elements in the action for logical processing and modify the state in the store, irrelevant It does not process the state and returns it as it is.
c. The store is responsible for storing the state and can be called back by the react api to publish actions.

From: Wang Namelos https://www.zhihu.com/question/41312576/answer/90782136


Let's start the actual combat operation: complete an operation of adding one and subtracting one, state is a number, action.type is the type of operation, reducer completes the specific operation, store is used to store state and publish action

First, to create a new store through createStore, you need to prepare the reducer (the counter in our reducer example is responsible for +1-1)

import {createStore} from 'redux'
// 1. Create a new store
// Created by reducer
// Generate new state based on old state and action
function counter(state=0 , action) {
    switch (action.type){
        case 'addition':
            return state + 1;
        case 'subtraction':
            return state - 1;
        default:
            return 10;
    }
}
// Create a new store, pass the prepared reducer processing function to createStore
const store = createStore(counter);

Then we print the state in the store now,


const init = store.getState();
console.log(init);   // 10

Next, you can dispatch events, pass actions, and determine which action of the reducer is hit by the type of action.

// dispatch the event to pass the action
store.dispatch({type: 'addition'});
console.log(store.getState());                  // 11
store.dispatch({type: 'addition'});
console.log(store.getState());                  // 12
store.dispatch({type: 'subtraction'});
console.log(store.getState());                  // 11

It is tedious to print once for each hit. We can add a listener

function listener() {
    const current = store.getState();
    console.log(`The current number is ${current}`);
}

// subscribe
store.subscribe(listener);
store.dispatch({type: 'addition'}); // now the number is 11
store.dispatch({type: 'addition'}); // now the number is 12
store.dispatch({type: 'subtraction'}); // now the number is 11

This way you don't have to play the console every time.


This is the basic usage of redux. More advanced usage will be shared with you in future articles.




Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326868813&siteId=291194637