從零搭建React框架--第三章狀態(tài)管理Redux、React-Redux

目錄

引言
第一章:項目創(chuàng)建、antd、less
第二章:路由攔截、路由嵌套
第三章:狀態(tài)管理 Redux
第四章:網(wǎng)絡請求、代理、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

在下面頁面中一共分為三部分:Header菜單中包括登錄用戶信息,系統(tǒng)消息。Left菜單主要含導航頁,菜單縮放。Content集成最近打開的功能,以及內容顯示。
本次以LeftMenu縮放展示Redux如何進行全局狀態(tài)管理。

首頁.png

核心代碼

定義首頁框架數(shù)據(jù)模型

const initHome: Frame.Frame = {
 menuList: [],           //導航菜單
 notificationsData: [],  //系統(tǒng)通知
 collapsed: false,       //菜單縮放
 menuSelectedKeys: [],   //菜單選中
 taglist: []             //最近打開菜單
}

左側菜單縮放action

//設置左側菜單縮放
const SET_LEFT_COLLAPSED = 'SET_LEFT_COLLAPSED'
export const setLeftCollapsed: (collapsed: boolean) => IAction<boolean> = (collapsed: boolean) => ({
  type: SET_LEFT_COLLAPSED,
  payload: collapsed
})

定義userReducer

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

export default userReducer

創(chuàng)建全局store


const reducers: Reducer<IStoreState, IAction<any>> = combineReducers<IStoreState>({
  user: userReducer,//登錄人信息
  frame: frameReducer//首頁框架信息
})
//thunk redux支持異步請求
const middleware: Middleware[] = [thunk]
//開發(fā)模式引入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(
  <ConfigProvider locale={zhCN}>
    <Provider store={store}>
      <AppRouter />
    </Provider>
  </ConfigProvider>,
  document.getElementById('root')
)`

LeftMenu使用狀態(tài)

通過 react-redux組建中useSelector獲取到全局store中Frame數(shù)據(jù)。

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

通過useDispatch方法獲取dispatch,進行菜單縮放狀態(tài)更新。

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

全部代碼

const LeftMenu: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const frameState: Frame.Frame = useSelector<IStoreState, Frame.Frame>(
    (state) => state.frame
  );
  return (
    <div>
      <Sider
        trigger={null}
        collapsedWidth={50}
        className="scroll ant-menu"
        style={{
          overflowX: "hidden",
          zIndex: 1000,
          height: `${document.body.offsetHeight - 50}px`,
        }}
        collapsed={frameState.collapsed}
        collapsible
      >
        //menu
          <div
            style={{
              width: "100%",
              cursor: "pointer",
              fontSize: "16px",
              borderTop: "1px solid #ccc",
              borderRight: "1px solid #f0f2f5",
            }}
            onClick={() => {
              //狀態(tài)點擊
              dispatch(setLeftCollapsed(!frameState.collapsed));
            }}
            className="btnbor"
          >
            <div style={{ marginLeft: "16px", padding: "10px 0" }}>
              {React.createElement(
                frameState.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined
              )}
            </div>
          </div>
        </div>
      </Sider>
    </div>
  );
};

export default LeftMenu;


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容