从零搭建React框架--第三章状态管理Redux、React-Redux

目录

引言
第一章:项目创建、antd、less
第二章:路由拦截、路由嵌套
第三章:状态管理 Redux
第四章:网络请求、代理、mockjs
第五章:webpack配置
第六章:Eslint

源码地址

https://github.com/dxn920128/cms-base

安装redux

npm install -S -D redux react-redux @types/react-redux redux-devtools-extension @types/redux-devtools-extension redux-logger @types/redux-logger redux-thunk
  • redux
  • react-redux
  • redux-devtools-extension 在调试中查看 Redux 中状态变化
  • redux-logger redux日志记录中间件
  • redux-thunk thunk中间件可以帮助在 Redux 应用中实现异步性

在下面页面中一共分为三部分:Header菜单中包括登录用户信息,系统消息。Left菜单主要含导航页,菜单缩放。Content集成最近打开的功能,以及内容显示。
本次以LeftMenu缩放展示Redux如何进行全局状态管理。

首页.png

核心代码

定义首页框架数据模型

const initHome: Frame.Frame = {
 menuList: [],           //导航菜单
 notificationsData: [],  //系统通知
 collapsed: false,       //菜单缩放
 menuSelectedKeys: [],   //菜单选中
 taglist: []             //最近打开菜单
}

左侧菜单缩放action

//设置左侧菜单缩放
const SET_LEFT_COLLAPSED = 'SET_LEFT_COLLAPSED'
export const setLeftCollapsed: (collapsed: boolean) => IAction = (collapsed: boolean) => ({
  type: SET_LEFT_COLLAPSED,
  payload: collapsed
})

定义userReducer

const userReducer: Reducer> = (
  state = initHome,
  action: IAction
) => {
  const { type, payload } = action
  switch (type) {
    case SET_LEFT_COLLAPSED:
      return {
        ...state,
        collapsed: payload
      }
    default:
      return state
  }
}

export default userReducer

创建全局store


const reducers: Reducer> = combineReducers({
  user: userReducer,//登录人信息
  frame: frameReducer//首页框架信息
})
//thunk redux支持异步请求
const middleware: Middleware[] = [thunk]
//开发模式引入redux-logger
if (process.env.NODE_ENV === 'development') {
  middleware.push(logger)
}

function createMyStore() {
  const store = createStore(reducers, composeWithDevTools(applyMiddleware(...middleware)))
  return store
}

const store = createMyStore()

export default store

在入口文件中引入全局store

ReactDOM.render(
  
    
      
    
  ,
  document.getElementById('root')
)`

LeftMenu使用状态

通过 react-redux组建中useSelector获取到全局store中Frame数据。

  const frameState: Frame.Frame = useSelector(
    (state) => state.frame
  );

通过useDispatch方法获取dispatch,进行菜单缩放状态更新。

 const dispatch = useDispatch();
 dispatch(setLeftCollapsed(!frameState.collapsed));

全部代码

const LeftMenu: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const frameState: Frame.Frame = useSelector(
    (state) => state.frame
  );
  return (
    
//menu
{ //状态点击 dispatch(setLeftCollapsed(!frameState.collapsed)); }} className="btnbor" >
{React.createElement( frameState.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined )}
); }; export default LeftMenu;

你可能感兴趣的:(从零搭建React框架--第三章状态管理Redux、React-Redux)