Umi3与Antd-Pro5中后台全栈项目实战(1)

简介: 0、前言使用umi3和antd pro5从零实现全栈中后台管理系统

0、前言

使用umi3和antd pro5从零实现全栈中后台管理系统

0-1、涉及技术栈

前端: TS 、 React、React Hooks、 umi3、antd-pro5后端:   express、mongodb、jwt**

0-2、实现的功能

  • 后端用户鉴权
  • 前端权限管理
  • 用户密码加密
  • 封装一套通用弹窗表单组件,实现新建、修改、详情功能
  • 用户登录注册(首次需要后端自己添加一条用户登录信息)

0-1、涉及技术栈

前端: TS 、 React、React Hooks、 umi3、antd-pro5后端:   express、mongodb、jwt**

0-2、实现的功能

  • 后端用户鉴权
  • 前端权限管理
  • 用户密码加密
  • 封装一套通用弹窗表单组件,实现新建、修改、详情功能
  • 用户登录注册(首次需要后端自己添加一条用户登录信息)

1、初始化前端项目

umi 官网coding网址

yarn create umi myapp
npm i 
npm run dev

1、设置config下的proxy代理

  dev: {
    '/api/': {
      target: "http://localhost:3000",
      changeOrigin: true,
      pathRewrite: { '^': '' },
    },
  },

2、登录

修改src/service/login.ts 接口改为/api/user/login

export async function fakeAccountLogin(params: LoginParamsType) {
  return request<API.LoginStateType>('/api/user/login', {
    method: 'POST',
    data: params,
  });
}

存储token pages/user/login/index.tsx

localStorage.setItem('token' , msg.token)

使用token services/user.ts

export async function queryCurrent() {
  return request<API.CurrentUser>('/api/currentUser',  headers: {
      Authorization :  'Bearer ' + `${localStorage.getItem('token')
      }`
    }
}

每次请求都带上token src/app.tsx

export const request: RequestConfig = {
  errorHandler,
  headers: { 
    Authorization :  'Bearer ' + `${localStorage.getItem('token')}`
  }
};

退出 RightContent/AvatarDropdown.tsx

 localStorage.removeItem('token')

3、pro5参考文档

procomponents.ant.design/components/…

4、实现一个用户管理

5、列表页

pages/ListTableList/index.tsx

import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Avatar } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import HandleForm from './components/HandleForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule } from './service';
import moment from 'moment';
/**
 * 操作提交
 * @param fields
 */
const handleSubmit = async (_id?: string, fields?: TableListItem) => {
  let title = _id ? '修改' : '新增';
  const hide = message.loading(`正在${title}`);
  try {
    if (_id) {
      await updateRule({
        _id,
        ...fields,
      });
    } else {
      await addRule({ ...fields });
    }
    hide();
    message.success(`${title}成功`);
    return true;
  } catch (error) {
    hide();
    message.error(`${title}失败`);
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: string[], _id: string) => {
  // console.log(selectedRows,_id,'selectedRows>>>>')
  const hide = message.loading('正在删除');
  // return
  try {
    await removeRule({
      _id: _id ? _id : selectedRows,
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败');
    return false;
  }
};
const TableList: React.FC<{}> = () => {
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentInfo, handleSaveCurrentInfo] = useState<TableListItem | null>(null);
  const [isDetail, setDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any>([]);
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '密码',
      dataIndex: 'password',
      hideInDescriptions: true, //详情页不显示
      hideInTable: true,
    },
    {
      title: '角色',
      dataIndex: 'access',
      search: false,
      filters: [
        { text: '普通用户', value: 'user' },
        { text: '管理员', value: 'admin' },
      ],
      valueEnum: {
        user: { text: '普通用户' },
        admin: { text: '管理员' },
      },
    },
    {
      title: '_id',
      dataIndex: '_id',
      sorter: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      search: false,
      hideInForm: true,
      render: (dom, entity) => {
        return <Avatar src={entity.avatar} alt="" />;
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      sorter: true,
      hideInForm: true,
      search: false,
      renderText: (val: string) => {
        if (!val) return '';
        return moment(val).fromNow(); // 绝对时间转化成相对时间
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      sorter: true,
      hideInForm: true,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            href="javascript:;"
            onClick={() => {
              handleModalVisible(true), handleSaveCurrentInfo(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            href="javascript:;"
            onClick={() => {
              handleModalVisible(true), handleSaveCurrentInfo(record), setDetail(true);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            href="javascript:;"
            onClick={async () => {
              await handleRemove([], record._id as 'string');
              // 刷新
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="用户管理"
        actionRef={actionRef}
        rowKey="_id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined />
            新增
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        columns={columns}
        form={{
          submitter: false,
        }}
        pagination={{ defaultPageSize: 5 }}
        rowSelection={{
          onChange: (selected, selectedRows) => {
            setSelectedRows(selected);
          },
        }}
      />
      <HandleForm
        onCancel={() => {
          handleModalVisible(false), handleSaveCurrentInfo({}), setDetail(false);
        }}
        modalVisible={modalVisible}
        values={currentInfo}
        isDetail={isDetail}
        onSubmit={async (values) => {
          const success = await handleSubmit(currentInfo?._id, values);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      ></HandleForm>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState, '');
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};
export default TableList;

pages/ListTableList/data.d.ts

export interface TableListItem {
  _id?: string;
  username?: string;
  password?: string;
  avatar?: string;
  access?: string;
  email?: string;
} 
export interface TableListPagination {
  total: number;
  pageSize: number;
  current: number;
}
export interface TableListData {
  list: TableListItem[];
  pagination: Partial<TableListPagination>;
}
export interface TableListParams {
  _id?: string;
  username?: string;
  password?: string;
  avatar?: string;
  access?: string;
  email?: string;
  pageSize?: number;
  currentPage?: number;
  filter?: { [key: string]: any[] };
  sorter?: { [key: string]: any };
}

pages/ListTableList/service.ts

import { request } from 'umi';
import { TableListParams } from './data.d';
export async function queryRule(params?: TableListParams) {
  return request('/api/user/account', {
    params,
  });
}
export async function removeRule(params: { _id: string|string[] }) {
  return request('/api/user/account', {
    method: 'DELETE',
    data: params
  });
}
export async function addRule(params: TableListParams) {
  return request('/api/user/account', {
    method: 'POST',
    data: {
      ...params
    },
  });
}
export async function updateRule(params: TableListParams) {
  return request(`/api/user/account?_id=${params._id}`, {
    method: 'PUT',
    data: {
      ...params
    },
  });
}

相关文章
|
前端开发 测试技术 数据安全/隐私保护
使用 React-Hook-Form 让你的表单天生强大
使用 React-Hook-Form 让你的表单天生强大
2361 0
|
10月前
|
边缘计算 Serverless 数据库
Next.js+Vercel+Turso:全栈开发者的终极免费套餐,让数据库查询快10倍、成本降90%!
Turso是基于libSQL(SQLite开源分支)的边缘分布式数据库,支持全球35+节点自动复制、嵌入式本地副本、多写入并发及向量搜索。兼容SQLite生态,查询延迟降至5ms,成本降低90%,免费版即够用。完美适配Next.js/Vercel等全栈场景。
1068 1
|
12月前
|
人工智能 安全 API
上手教程:聊聊怎么用阁下AI的API
上手教程:聊聊怎么用阁下AI的API
|
12月前
|
缓存 监控 前端开发
前端静态资源加载优化
本文系统讲解前端静态资源加载优化,涵盖资源压缩、缓存策略、CDN加速、懒加载、预加载、HTTP/2升级等十大核心维度,结合Webpack配置与实战案例,助力开发者提升页面性能,打造极致用户体验。
829 0
|
SQL 监控 数据可视化
完全开源!国内首个完全开源JAVA企业级低代码平台
JeeLowCode 是一款专为企业打造的 Java 企业级低代码开发平台,通过五大核心引擎(SQL、功能、模板、图表、切面)和四大服务体系(开发、设计、图表、模版),简化开发流程,降低技术门槛,提高研发效率。平台支持多端适配、国际化、事件绑定与动态交互等功能,广泛适用于 OA、ERP、IoT 等多种管理信息系统,帮助企业加速数字化转型。
|
缓存 JavaScript 前端开发
Vue项目卡顿慢加载?这些优化技巧告诉你!(一)
Vue项目卡顿慢加载?这些优化技巧告诉你!
6186 0
|
SQL Java 数据库连接
既生瑜何生亮,浅析下层出不穷的新ORM框架: MyBatis-Flex
这里先说说我的观点哈,仅是个人观点哦,不喜勿喷。现在这些框架层出不穷,其实吧个人感觉没必要过度关注,因为这些框架并没有完完全全做到推陈出新,反倒是有一点互相“学习copy”的感觉,并没有那么新颖强大、从无到有的一个过程。那说回今天的主题ORM框架,在Java后端技术栈里面我们都知道`MyBatis`是主流的ORM框架,现在很多公司都在使用着,后来在`MyBatis`基础上出现了两个比较主流的增强框架`Mybatis-Plus`和`Fluent-MyBatis`
1814 0
|
缓存 自然语言处理 JavaScript
JavaScript中闭包详解+举例,闭包的各种实践场景:高级技巧与实用指南
闭包是JavaScript中不可或缺的部分,它不仅可以增强代码的可维护性,还能在模块化、回调处理等场景中发挥巨大作用。然而,闭包的强大也意味着需要谨慎使用,避免潜在的性能问题和内存泄漏。通过对闭包原理的深入理解以及在实际项目中的灵活应用,你将能够更加高效地编写出简洁且功能强大的代码。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
JSON JavaScript 前端开发
TypeScript(十六)配置相关(tsconfig配置)
TypeScript(十六)配置相关(tsconfig配置)
1130 1
|
Dart 开发工具 Windows
Dart安装(Winodws)
Dart安装(Winodws)
953 0