【青训营】- Redux · 极简教程

1,112 阅读1分钟

前言:

Redux : JS 应用的状态容器,提供可预测的状态管理, 当你有数据需要全局统一管理,并且渲染时, 你可以考虑她。

知识点:

  1. createStore 创建store
  2. reducer 初始化、修改状态函数
  3. getState 获取状态值
  4. dispatch 提交更更新
  5. subscribe 变更更订阅

使用步骤:

1. 准备工作 (处理逻辑 和 订阅)

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)

tips: combineReducers 可以合并多个 reducer , 有利于代码解耦 以及 分工合作; 入参为一个对象, 在调用 getState 时, 返回的就是这个对象的对应的reducer之后的state值.

2. 消费与发布

const ReduxPage = props => {
  // 获取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>
  </>)
}

tips: dispatch 的 type 要唯一, 不然符合条件的都会触发

tips: 此时你会发现在更新数据方面,用起来贼不爽, 因此 react-redux应运而生

Redux模型