Basic concepts of Redux

What is a Redux?
  • State management tool
  • 2 KB size
  • Mainly used in React, but can also be used in other JS frameworks
  • All states are stored in a single store that can be pulled from if needed
Why redux?
  • State sharing across Components (especially between sibling components, no redux needs to write a state in the parent component for sibling components to share the state)
  • A state needs to be available anywhere
  • A component needs to change global state
  • One component needs to change the state of another component
Redux a few concepts
  • Store: Stores the state of the entire application. Each component can read any state in the store
CreateStore import {createStore} from'redux'; const store = createStore(fn); // read state const state = store.getState()Copy the code
  • Action: an event that is the only way a view can send data to a store. This event is triggered by the store.disptach() method
const ADD_TODO = 'add TODO;

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

const action = addTodo('Learn Redux');
Copy the code
  • Reducer: a pure function that returns a new state that was created after the action was executed — the Store must present a new state after receiving the action so that the View will change. This State calculation process is called Reducer.
Const createStore = (reducer) => {let state;
  letlisteners = []; const getState = () => state; Reducer = (action) => {state = reducer(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener);return () => {
      listeners = listeners.filter(l => l !== listener);
    }
  };

  dispatch({});

  return { getState, dispatch, subscribe };
};
Copy the code

Technical points in Redux
  • WithRouter connects actions and reducer through HOC (High Order Component) of React
  • Functional programming: The Reducer of Redux must be a pure function, while store and action should be immutable. The replication state loses performance to a certain extent, but at the millisecond level, it can be ignored

Synchronize action processing

The todo list is used repeatedly in the Redux tutorial, which is a typical synchronous action. Whenever a disptach action is disptach, the state is immediately updated (setState is asynchronous, of course).

Processing of asynchronous actions

  • In the case of API request data, request and receive need to be defined as two different actions. The user trigger is request, and the API callback trigger receive- refer to the official documentation
  • Typically, asynchronous processing uses middleware such as Redux-Thunk or Redux-saga. What they do is wrap dispatches. Request actions are triggered by the View, and receive actions are triggered by these middleware