Preface:

Redux: JS application state container, provides predictable state management, when you have data to manage globally, and rendering, you can consider her.

Knowledge:

  1. CreateStore create store
  2. The reducer state function is initialized and modified
  3. GetState Gets the status value
  4. Dispatch delivers more updates
  5. Subscribe change more subscribe

Use steps:

1. Preparation (processing logic and subscriptions)

import { createStore, combineReducers } from 'redux'

// I. reducer
const counterReducer = (state = 0, action) = > {
  switch (action.type) {
    case 'counter/ADD':
      return state + action.payload || 1
    case 'MINUS':
      return state - 1
    default:
      return state
  }
}

const todoReducer = (state = 'todo list', action) = > {
  switch (action.type) {
    case 'todo/ADD':
      return state + 'add'
    default:
      return state
  }
}

// II. createStore

const rootReducer = combineReducers({
  todo: todoReducer,
  counter: counterReducer
})

const store = createStore(rootReducer)

// III. subscribe

function render() {
  ReactDOM.render(
    <React.StrictMode>
      <ReduxPage />
    </React.StrictMode>.document.getElementById('root')); } render() store.subscribe(render)Copy the code

Tips: combineReducers can combine multiple Reducer, which facilitates code decoupling and division of labor and cooperation; The input is an object, and when getState is called, it returns the state value after the corresponding reducer of the object.

2. Consumption and distribution

const ReduxPage = props= > {
  / / for the state
  
  const state = store.getState()
  
  return (<>
    <p>{state.todo}</p>
    <p>{state.counter}</p>
    <button onClick={()= >State store.dispatch({type: 'counter/ADD', payload: 2})}}>counter ADD</button>
  </>)}Copy the code

Tips: The type of dispatch must be unique, otherwise all that meet the conditions will be triggered

Tips: At this point, you'll find that the react-Redux doesn't work very well for updating data, hence the react-Redux

Redux model