react、redux、reduxThunk二次封装

90 阅读1分钟

1. Redux 核心思想

Redux 是一个 可预测的状态管理工具,适合管理复杂的全局状态。
它有三个核心原则:

  1. 单一数据源:整个应用只有一个 Store 来存储全局状态。
  2. 状态只读:不能直接修改 state,只能通过 action。
  3. 使用纯函数修改:reducer 是纯函数,接收旧 state + action,返回新 state。

2. Redux 基本流程

  1. 创建 Store:保存全局状态。
  2. 定义 Reducer:根据 action 修改 state。
  3. 定义 Action:描述发生了什么。
  4. 在组件中使用:通过 useSelector 获取数据,用 useDispatch 分发 action。

使用方法

1.在main.js中引入

import store from '@/packages/store'

2。store下的index文件

import {
  legacy_createStore,
  combineReducers,
  compose,
  applyMiddleware,
} from "redux";
import reduxThunk from "redux-thunk";
import handleNum from "../../config/store/NumStatus/reducer";
import handleArr from "../../config/store/ArrStatus/reducer";
import handleXxxx from "../../config/store/XxxxStatus/reducer";

// 组合各个模块的reducer
const reducers = combineReducers({
  handleNum,
  handleArr,
  handleXxxx,
});

// 创建数据仓库
// window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 为了让浏览器正常使用redux-dev-tools插件
// const store = legacy_createStore(reducers,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

// 判断有没有__REDUX_DEVTOOLS_EXTENSION_COMPOSE__这个模块
let composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
  : compose; //rt

// 把仓库数据,浏览器redux-dev-tools,还有reduxThunk插件关联在store中
const store = legacy_createStore(
  reducers,
  composeEnhancers(applyMiddleware(reduxThunk))
);
export default store;

3.packages/store创建XxxStatus文件夹 index.ts

const store = {
  state:{
    // 放数据
   
  },
  actions:{
    // 放同步方法
   
  },
  asyncActions:{
    // 放异步方法
   
  },
  actionNames:{}
}
let actionNames = {} 
for(let key in store.actions){
  actionNames[key] = key
}
store.actionNames=actionNames;

export default store

reducer.ts

import handler from "./index"


let reducer = (state = {...handler.state},action:{type:string})=>{

    let newState = JSON.parse(JSON.stringify(state))

    for(let key in handler.actionNames){
      
      if(action.type===handler.actionNames[key]){
        handler.actions[handler.actionNames[key]](newState,action);
        break;
      }
    }
    
    return newState
}
export default reducer