Welcome to pay attention to my public account “Life Code”

The principle flow chart is as follows:

How to understand the Redux principle

How to understand the Redux principle

  • So let’s think about how do we create a store

  • What does the store support us to do

  • Get the data state in the store

  • You can update the state of data in the store

  • How to update data state in store

  • How does the external know that the data has been updated by subscription

Through the above steps, we can draw the following flow chart, or schematic diagram:

Then we can implement the code:

import { createStore } from 'redux';

// How to create a store
// What does the store support
// 1. Obtain the state of the data in store
// 2. You can update the state of the data in the store
// 3. How to update the status of data in store

// State data in store
let state = {
  num: 10
}

// What type of operation is required
let action1 = {
  type: 'ADD_ONE'.num: 1
}

let action2 = {
  type: 'SQUARE',}let action3 = {
  type: 'ADD_TWO'.num: 2
}

// Because we cannot directly modify or overwrite the store data state, we can only return the new state
// We need reducer to help us do these things

let reducer = (state = {num: 2}, action) = > {
  let num
  switch(action.type) {
    case "ADD_ONE":
      num = state.num + action.num
      return { num }
    case "ADD_TWO":
      num = state.num + action.num
      return { num }
    case "SQUARE":
      num = state.num * state.num
      return { num }
    default:
      return state
  }
}

// Then use createStore to connect to the Reducer

let store = createStore(reducer)

// 外部如果获取 store 里面的 state

console.log("store.getState",store.getState())

// Then how does the external update the internal value
// Can only be updated via dispatch

console.log("store.dispatch(action1)", store.dispatch({type: "ADD_ONE"}))

console.log("store===>", store)

// What if there are multiple reducer's?
// Cominereducers ({reducer})
Copy the code

So how does the external view layer know if the state in the store has been updated?

Redux takes a subscription approach

// How does the outside world know that the state in the store has been updated
// Redux uses subscriptions
store.subscribe(function(){
  console.log("I've been updated.")})// What if there are multiple reducer's?
// Cominereducers ({reducer})

// What if there is middleware
// Redux provides applyMiddleware
Copy the code