React專案整合Immutable.js

Awbeci發表於2019-06-01

1、前言

本文章專案的依賴包及其版本如下:

Package Name Version
antd ^3.16.6
connected-react-router ^6.4.0
customize-cra ^0.2.12
immutable ^4.0.0-rc.12
react ^16.8.6
react-app-rewired ^2.1.1
react-redux ^7.0.3
react-router-config ^5.0.0
react-router-dom ^5.0.0
react-scripts 3.0.1
redux ^4.0.1
redux-logger ^3.0.6
redux-persist ^5.10.0
redux-persist-expire ^1.0.2
redux-persist-transform-immutable ^5.0.0
redux-saga ^1.0.2

2、準備工作,搭建專案

下面是我的專案結構,每個人或者每個公司都有自己的目錄架構,這裡我的只供大家參考,另外搭建專案過程和介紹如何使用immutable.js不是本文章的重點,如何使用immutable.js以及本文章相關程式碼後面我會給出,如果有疑問歡迎大家在下面留言

|-- App.js
|-- index.js
|-- serviceWorker.js
|-- assets
|   |-- audio
|   |-- css
|   |   |-- App.scss
|   |   |-- base.scss
|   |   |-- index.css
|   |   |-- override-antd.scss
|   |-- image
|   |   |-- Welcome.png
|   |   |-- awbeci.png
|   |   |-- bgLogo.png
|   |   |-- hiy_logo.png
|   |   |-- indexPop1.png
|   |   |-- indexPop2.png
|   |   |-- logo.png
|   |   |-- logoX.png
|   |   |-- right.png
|   |-- video
|-- components
|   |-- HOC
|   |   |-- loading.js
|   |-- common
|   |-- layout
|       |-- AppRoute.js
|       |-- LayoutPage.js
|       |-- Loading.js
|       |-- MasterPage.js
|       |-- RouterView.js
|       |-- SideMenu.js
|       |-- layoutPage.scss
|       |-- masterPage.scss
|-- config
|   |-- base.conf.js
|-- context
|   |-- themeContext.js
|-- pages
|   |-- DepartmentManage.js
|   |-- Index.js
|   |-- NoFound.js
|   |-- NoPermission.js
|   |-- UserManage.js
|   |-- login
|       |-- Login.js
|       |-- login.scss
|-- redux
|   |-- actions
|   |   |-- authAction.js
|   |   |-- layoutPageAction.js
|   |-- middleware
|   |   |-- authTokenMiddleware.js
|   |-- reducers
|   |   |-- authReducer.js
|   |   |-- index.js
|   |   |-- layoutPageReducer.js
|   |-- sagas
|   |   |-- authSaga.js
|   |   |-- index.js
|   |-- store
|   |   |-- index.js
|   |-- thunks
|-- router
|   |-- index.js
|-- service
|   |-- apis
|   |   |-- 1.0
|   |       |-- index.js
|   |       |-- urls.js
|   |-- mocks
|   |   |-- 1.0
|   |       |-- index.js
|   |       |-- testMock.js
|   |-- request
|       |-- ApiRequest.js
|       |-- MockRequest.js
|-- test
|   |-- App.test.js
|-- utils

3、整合immutable.js

此專案除了依賴包要配置之外,只有redux下的reducer相關檔案會設定成immutable.js普通的react元件我沒有設定成immutable.js

App.js

import { ConnectedRouter } from "connected-react-router";
//換成
import { ConnectedRouter } from "connected-react-router/immutable";

store->index.js

import { routerMiddleware } from "connected-react-router";
//換成
import { routerMiddleware } from "connected-react-router/immutable";
//新增
import immutableTransform from "redux-persist-transform-immutable";

const persistConfig = {
  transforms: [encryptor],
  //換成
  transforms: [
    immutableTransform()
    // 注意:必須要註釋encryptor否則會報錯
    // encryptor
  ],
  ...
}

redux->reducers->index.js

import { connectRouter } from "connected-react-router";
//換成
import { connectRouter } from "connected-react-router/immutable";

redux->reducers->authReducer.js

//新增
import { Map, fromJS, merge } from "immutable";

const initState = {
  user: null,
  token: ""
};

[authTypes.AUTH_SUCCESS]: (state, action) => {
      return Object.assign({}, state, { user: action.data.user, token: action.data.token });
    },
    [authTypes.SIGN_OUT]: (state, action) => {
      return Object.assign({}, state, {
        user: null,
        token: ""
      });
    }
//換成
const initState = fromJS({
  user: null,
  token: ""
});

    [authTypes.AUTH_SUCCESS]: (state, action) => {
      return state.merge({
        user: action.data.user,
        token: action.data.token
      });
    },
    [authTypes.SIGN_OUT]: (state, action) => {
      return state.merge({
        user: null,
        token: ""
      });
    }

redux->reducers->layoutPageReducer.js

//新增
import { Map, fromJS, merge, List } from "immutable";

const initState = {
  index: "126",
  subIndex: "",
  collapsed: false,
  menus: [],
  loading: false
};
[layoutPageTypes.SAVE_MENU_INDEX]: (state, action) => {
      const { keyPath } = action.payload;
      let index = keyPath[0];
      let subIndex = null;
      if (keyPath.length === 2) {
        subIndex = keyPath[1];
      }
      return Object.assign({}, state, {
        index: index,
        subIndex: subIndex
      });
    },
    [layoutPageTypes.SAVE_MENU_COLLAPSED]: (state, action) => {
      const { collapsed } = action.payload;
      return Object.assign({}, state, {
        collapsed: collapsed
      });
    },
    [layoutPageTypes.GET_MENUS]: (state, action) => {
      const { menus } = action;
      return Object.assign({}, state, {
        menus: menus
      });
    }
//換成
const initState = fromJS({
  index: "126",
  subIndex: "",
  collapsed: false,
  menus: List()
});

[layoutPageTypes.SAVE_MENU_INDEX]: (state, action) => {
      const { keyPath } = action.payload;
      let index = keyPath[0];
      let subIndex = null;
      if (keyPath.length === 2) {
        subIndex = keyPath[1];
      }
      return state.merge({
        index: index,
        subIndex: subIndex
      });
    },
    [layoutPageTypes.SAVE_MENU_COLLAPSED]: (state, action) => {
      const { collapsed } = action.payload;
      return state.merge({
        collapsed: collapsed
      });
    },
    [layoutPageTypes.GET_MENUS]: (state, action) => {
      const { menus } = action;
      return state.merge({
        menus: menus
      });
    }

middleware->authTokenMiddleware.js

//新增
import { fromJS } from "immutable";

if (action.type === REHYDRATE) {
    if (action.payload && action.payload.authReducer && action.payload.authReducer.token) {
      ApiRequest.setToken(action.payload.authReducer.token);
    }
  }
//換成
if (action.type === REHYDRATE) {
    if (typeof action.payload !== "undefined") {
      let authReducer = action.payload.authReducer;
      if (authReducer) {
        const token = authReducer.get("token");
        ApiRequest.setToken(token ? token : null);
      }
    }
  }

components->layout->LayoutPage.js

<span style={{ marginLeft: 8 }}>{authReducer.user ? authReducer.user.name : "使用者"}</span>

<Switch>{authReducer.token ? renderRoutes(routes) : <Redirect to="/login" />}</Switch>
//換成
<span style={{ marginLeft: 8 }}>{authReducer.get("user") ? authReducer.getIn(["user", "name"]) : "使用者"}</span>

<Switch>{authReducer.get("token") ? renderRoutes(routes) : <Redirect to="/login" />}</Switch>

components->layout->SideMenu.js

let menus = layoutPageReducer.menus;

<Menu
          theme="light"
          defaultSelectedKeys={[layoutPageReducer.index]}
          selectedKeys={[layoutPageReducer.index]}
          defaultOpenKeys={[layoutPageReducer.subIndex]}
          mode="inline"
          className="sider-menu-container"
          inlineCollapsed={layoutPageReducer.collapsed}
          onClick={this.clickSidebarMenu}
        >
          {newMenus}
        </Menu>
//換成
let menus = layoutPageReducer.get("menus");

        <Menu
          theme="light"
          defaultSelectedKeys={[layoutPageReducer.get("index")]}
          selectedKeys={[layoutPageReducer.get("index")]}
          defaultOpenKeys={[layoutPageReducer.get("subIndex")]}
          mode="inline"
          className="sider-menu-container"
          inlineCollapsed={layoutPageReducer.get("collapsed")}
          onClick={this.clickSidebarMenu}
        >
          {newMenus}
        </Menu>

components->layout->AppRoute.js

Authentication() {
    return this.props.store.authReducer.token ? <Redirect to="/" /> : <Login />;
  }
//換成
    return this.props.store.authReducer.get("token") ? <Redirect to="/" /> : <Login />;

4、啟動專案看是否整合成功

命令列執行:yarn start

clipboard.png

清除下快取尤其是localstorage,如果看到上面的登入頁面那麼恭喜你配置成功!

5、redux-logger 列印immutable.js日誌

下面我們來看看redux-logger列印的日誌跟我們不使用immutable.js有什麼區別?
clipboard.png
如上圖所示,列印的日誌資料就是immutable.js的相關資料,但是我們會發現閱讀性不是太好,這裡我們安裝一個格式化immutable.js的日誌資料的Chrome外掛,安裝一下即可,之前我有寫過一篇文章教你怎麼使用這個外掛,點選跳轉閱讀,安裝好之後,我們再來檢視資料,如下所示:

clipboard.png

是不是增加了日誌的可閱讀性,到此我們整合Immutable.js就至此結束,歡迎大家在下面留言交流!

6、總結

1)上面是教你如何把現有專案整合immutable.js,如果你是新專案,上面有些配置其實是不用管的;
2)上面的整合原則:把原生的寫法改成immutable.js的寫法即可!;
3)這裡我用到了redux-persist,如果你沒有用到這個包,那麼你就可以不用安裝redux-persist-transform-immutable,換成redux-immutable包即可,具體如何操作,官方文件上面有講,這裡就不多說了。
4)演示地址本文章程式碼,另外本文章程式碼對應github上面的immutable.js分支,而演示地址對應的是master分支!

7、引用

1.Immutable.js瞭解一下?
2.React引用資料型別與immutable.js的使用例項
3.react 使用的小建議
4.Immutable.js 以及在 react+redux 專案中的實踐
5.React Native Redux、redux-persist、immutable.js 結合實踐
6.Error when using redux-persist with redux-immutable
7.大話immutable.js
8.Immutable.js 以及在 react+redux 專案中的實踐
9.Immutable.js與React,Redux及reselect的實踐
10.如何用React+Redux+ImmutableJS進行SPA開發
11.immutable.js 在React、Redux中的實踐以及常用API簡介
12.筆記, immutable-js 基礎操作
13.Immutable.js 到底值不值得用?
14.Immutable 詳解及 React 中實踐
15.Immutable.js與React,Redux及reselect的實踐

相關文章