Redux

  • The core source code is concise
  • It solves the data processing problem of multi – interaction and multi – data source
  • Application scenario: Component status sharing, one component needs to change the global status, one component needs to change the status of another component
  • Similar to VUEX, it is actually a data transit zone

The problem

  • We can see that sharing using an object data, in which the shared state can be arbitrarily modified, the behavior of the program becomes very unpredictable. So we raised the bar for modifying the data: everyone had to passdispatchTo perform the modification, and you need to conspicuously pass it an action objectaction.
  • It turns out that every time you modify the data, you have to render manually: using sub-pub mode, throughstore.subscribeSubscribe to data render events that automatically render views every time data is updated
  • The performance of “re-render view” was found to be poor, so “Objects of shared structure” was introduced to solve the problem. Just make simple judgments at the beginning of each render function to avoid repeating the same data.
  • To optimize thestateChangerReducer is a pure function defined as reducer, whose function is responsible for initializationstateAnd according to thestateandactionCompute new with shared structuresstate.

Redux exists to solve the problem of accessing shared data and providing an API to modify it.

The core concept

Store: storage container state: stores basic data snapshots. Action: Update the data in state, we need to initiate an action Reducer: series the action and state so that we can make an action on a state and return this new state.

Updating the state according to the Action object is the whole idea of Redux.

The three principles

  1. Single data source: The state of the entire application is stored in an object tree that exists in a single store.
  2. State is read-only: the only way to change State is to trigger an action, which is a generic object that describes events that happen easily.
  3. Use pure functions to modify (with parameters state and Action) : To describe how the action changes the State Tree, you need to write reducers. It accepts the previous state and action and returns the new state, i.e(state, action) => state.

Redux design idea

  1. A Web application should be a state machine: there is a one-to-one correspondence between views and states
  2. All states are stored in one object

Basic API

Store

The object that stores the data can be thought of as a container, and there can only be one Store for the entire application.

import {createStore} from 'redux'
const store = createStore(fn) // Store is an object with two keys, getState and dispatch. Its corresponding value is a function (getState() has no argument, and dispatch(action) is a JS object describing the action).
Copy the code
  • fnStateChanger is a function called stateChanger with a list of arguments (state, action) to usePerform the action on the current state
  • CreateStore returns an object of the form {getState: ()=> state, dispatch: (action) => stateChanger(state, action)}

State

Represents a data snapshot of a node at a certain time. You can get the current State by calling store.getState().

Action

State changes need to be handled through Action. An Action usually has a name of Type and a payload of information it carries.

  • To simplify Action generation, you can use a function that returns an Action object, called Action Creator

store.dispatch()

Is the only way to issue an Action in a View. Keep the data up to date and the page rendered up to date through the publish-subscribe model.

reducer()

When the Store receives the Action, it calculates the new State from both the State and the Action. If no State is received, an initial data is returned.

Reducer is a pure function, so the same State and Action must have the same result.

store.subscribe()

  • Store allows usestore.subscribeMethod sets a listener function that is automatically executed whenever State changes. So simply put the component’s render function (render/setState) into the listener to implement automatic rendering of the page.
  • store.subscribeReturns a function that can be called to unlisten.

The context of the React. Js

A component can use the getChildContext method to return an object that defines the context of the subcomponent tree. The component providing the context must provide childContextTypes as the declaration and validation of the context. Child components can access data in this object through this.context.

.

Pure function Pure function

A function whose returns depend only on its arguments and have no side effects during execution is called a pure function.

  1. Returns results only depending on its own parameters
  2. There are no side effects
  • Pure functions are very strict, we can do almost nothing but calculate data, and we can’t rely on data other than parameters when we calculate.
  • Meaning: Very reliable, no unexpected behavior, no external impact. Convenient debugging and testing.

Objects that share a structure

ES6’s extended operators can be used for shallow copies of objects.

const obj = { a: 1.b : 2 }
constobj2 = { ... obj,b : 3.c: 4 } {a: 1, b: 3, c: 4}, the new b overwrites the old B
Copy the code

Compile Reducer habits

  1. Define the action types
  2. Write the reducer
  3. Action Creators related to this Reducer

Redux template writing

// Define a reducer
function reducer (state, action) {
    /* Initialize state and switch case */
}

/ / store
const store = createStore(reducer)

// Listen for data changes and re-render the page
store.subscribe(() = > renderApp(store.getState()))

Render the page for the first time
renderApp(store.getState())

// Now you can dispatch some actions, and the page will update automatically
store.dispatch(...)
Copy the code

Reference: React.js little book