首页 » 记事本 » 用Dva Model优化路由配置功能

用Dva Model优化路由配置功能

最近业务中的中后台系统基本上都是采用Ant Design Pro开发,业务中路由配置模块功能过于复杂,如果组件通信只通过React props实在是痛苦不堪。Ant Design Pro中内置了dva,dva 通过 model 的概念把一个领域的模型管理起来,包含同步更新 state 的 reducers,处理异步逻辑的 effects,订阅数据源的 subscriptions 。

拆分组件

业务逻辑概览

业务逻辑概览

设计Model

export default {
  namespace: 'routeConfig',
  state: {
    transfer: [],
    canvasData: [],
    isVisibleServiceList: false,
    serviceSearchParams: [],
    urbanOrOutside: 'urban',
    transferIndex: 0,
  },

  effects: {
    * isVisibleServiceList({ payload }, { put }) {
      yield put({
        type: 'isVisible',
        payload,
      });
    },
  },

  reducers: {
    addTransfer(state, { payload }) {
      return {
        ...state,
        transfer: [...state.transfer, payload],
      };
    },
    updateTransfer(state, { payload }) {
      const { index, name, code } = payload;
      const transfer = JSON.parse(JSON.stringify(state.transfer));
      transfer[index].name = name;
      transfer[index].code = code;
      return {
        ...state,
        transfer,
      };
    },
    isVisible(state, { payload }) {
      return {
        ...state,
        isVisibleServiceList: payload,
      };
    },
    addTransferMultiple(state, { payload }) {
      return {
        ...state,
        transfer: payload,
      };
    },
    updateCanvasData(state, { payload }) {
      return {
        ...state,
        canvasData: payload,
      };
    },
    deleteTransfer(state, { payload }) {
      const transfer = JSON.parse(JSON.stringify(state.transfer));
      transfer.splice(payload, 1);
      return {
        ...state,
        transfer,
      };
    },
    urbanOrOutside(state, { payload }) {
      return {
        ...state,
        urbanOrOutside: payload,
      };
    },
    transferIndex(state, { payload }) {
      return {
        ...state,
        transferIndex: payload,
      };
    },
    handleState(state, { payload }) {
      return {
        ...state,
        handleState: payload,
      };
    },
    updateIndex(state, { payload }) {
      return {
        ...state,
        updateIndex: payload,
      };
    },
  },
};

触发action,实现增删改:

onChange = (value, selectedOptions, i) => {
  const { dispatch } = this.props;
  dispatch({
    type: 'routeConfig/updateTransfer',
    payload: {
      index: i,
      code: selectedOptions[1].code,
      name: value[1],
    },
  });
};
add = () => {
  const { dispatch } = this.props;
  dispatch({
    type: 'routeConfig/addTransfer',
    payload: { code: Date.now() },
  });
};
delete = (i) => {
  const { dispatch, onDelete } = this.props;
  dispatch({
    type: 'routeConfig/deleteTransfer',
    payload: i,
  });
  if (onDelete) {
    onDelete();
  }
};

绑定 State 到 View:

function mapStateToProps({ routeConfig }) {
  const { transfer } = routeConfig;
  return { transfer };
}

export default connect(mapStateToProps)(Transfer);

实际的线上业务逻辑比上面看到的要复杂数倍,不再详述。

其他功能

部分逻辑图

部分逻辑图

此文章发表在 记事本 标签为 . 将固定链接加入收藏.