Redux learning notes – Vol.1 – Introduction

Time:2022-1-14

Write in front

This series is my synchronous notes when learning redux. The learning materials are:Redux Chinese document

motivation

Background: single page application,JS needs to manage many states
Two concepts: change and asynchrony
Combination of react and react: react prohibits asynchrony and directly operates DOM in the view layer, and Redux processes the data in state.
Purpose:Redux tries to make state changes predictable

Three principles

Single data source

Pay attention to understanding:The state of the entire application is stored in an object tree, and the object tree exists in only one store.

State is read-only

The only way to change state is to trigger action, which is a common object used to describe events that have occurred.

store.dispatch({
    type: 'ADD_ Item ', // specify the required type attribute in an action object
    index: 1
});

Use pure functions to perform modifications

To describe how an action changes a state tree, you need to writereducers
What are reducers?

Pure function, such as: (state, action) = > State

As the application becomes larger, pay attention to splitting a large reducer into multiple small reducers to operate different parts of the state tree independently.

//reducer 1
function visibilityFilter(state = 'SHOW_ALL', action){
    switch (action.type){
        case 'SET_VISIBILITY_FILTER':
            return action.filter;
        Default: // must exist! Otherwise, undefined will be returned
            return state;
    }
}

//reducer 2
function todos(action = [], action){
    switch (action.type){
        case 'ADD_TODO':
            return [
                ... State, // ES6 great method!
                {
                    text: action.text,
                    complete: false
                }
            ];
        case 'COMPLETE_TODO':
            return state.map((todo, index) => {
                if (index == action.index){
                    return Object.assign({}, todo, {
                        complete: true
                    });
                }
                return todo;
            });
        default:
            return state;
    }
}

import { combineReducers, createStore } from 'redux';
let reducer = combineReducers({ visbilityFilter, todos });
let store = createStore(reducer);

Next: Redux learning notes – Vol.2 – Basics

Recommended Today

Geometric interpretation of “feature space”

Geometric interpretation of “characteristic space”_ Beep beep beep_ bilibili     Note: 1.xAll vectors on the axis are the eigenvectors of matrix A. after being acted by a, they are magnified twice. 2.xThe axis is a one-dimensional space.The basis of this one-dimensional space can be a vector (1,0). 3. There are many, many, many eigenvectors […]