前端分层架构实践

747 阅读1分钟

1. 前端分层架构

  • Page 负责与用户直接打交道:渲染页面、接收用户的操作输入,侧重于展示型交互逻辑
  • Model 负责处理业务逻辑,为Page做数据、状态的读写、变换、暂存等
  • Service 负责与HTTP接口对接,进行纯粹的数据读写

2. 使用DVA进行数据分层管理

dva 是基于redux、redux-saga和react-router的轻量级前端框架 2.1 umi配置开启dva功能

// 导出一个对象, 暂时设置为空对象,后面再填充内容
export default {
  plugins: [
    ['umi-plugin-react', {
      // 暂时不启用任何功能
      dva: true // 开启dva功能
    }]
  ]
};

2.2 定义model层数据

export default {
  namespace: 'list',
  state: {
    data: [1, 2, 3]
  },
  reducers: {
    addNewData: function (state) {
      let newArr = state.data;
      newArr.push(newArr.length + 1);
      // 通过return 返回更新后的数据
      console.log(state.data);
      return {
        data: newArr
      }
    }
  }
}

2.3 将page和model进行绑定

import React from 'react';
import { connect } from 'dva';

const namespace = 'list';

// 说明: 第一个回调函数,作用: 将page层和model层进行连接,返回model中的数据
// 并且, 将返回的数据, 绑定到this.props
// 接受第二个函数,这个函数的作用: 将定义的函数绑定到this.props中
// 调用model层中定义的函数
@connect((state) => {
  return {
    dataList: state[namespace].data
  }
}, (dispatch) => { // dispatch的作用: 可以调用model层定义的函数
  return {  // 将返回的函数,绑定到this.props中
    add: function () {
      dispatch({ // 通过调用model中定义的函数, 通过type属性 指定函数名, 格式:namespace/函数名
        type: namespace + "/addNewData"
      });
    }
  }
})
class List2 extends React.Component {

  constructor(props) { // 构造函数中必须要props参数
    super(props); // 调用父类的构造方法
  }
  render() {
    return (
      <div>
        <ul>
          {
            // 遍历值
            this.props.dataList.map((value, index) => {
              return <li key={index}>{value}</li>
            })
          }
        </ul>
        <button onClick={
          () => { // 1. 为按钮添加点击事件
            this.props.add();
          }
        }>
          点击添加
        </button>
      </div>
    );
  }

}

export default List2;