Selaa lähdekoodia

单个页面表格 查询、删除、修改

tianyunperfect 5 vuotta sitten
vanhempi
commit
d122b628cd

+ 1 - 8
src/pages/ListTableList/index.tsx

@@ -182,14 +182,7 @@ const TableList: React.FC<{}> = () => {
             </Dropdown>
           ),
         ]}
-        tableAlertRender={(selectedRowKeys, selectedRows) => (
-          <div>
-            已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
-            <span>
-              服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万
-            </span>
-          </div>
-        )}
+
         request={(params) => queryRule(params)}
         columns={columns}
         rowSelection={{}}

+ 48 - 25
src/pages/ModelList/_mock.ts

@@ -1,30 +1,53 @@
+// eslint-disable-next-line import/no-extraneous-dependencies
 import {Request, Response} from 'express';
+import {parse} from 'url';
+import {TableListItem, TableListParams} from './data.d';
 
+// mock tableListDataSource
+const genList = (current: number, pageSize: number) => {
+  const tableListDataSource: TableListItem[] = [];
 
-export default {
-  'GET /api/uploadModel': (req: Request, res: Response) => {
-    res.json(
-      {
-        flag: true,
-        data: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png'
-      }
-    );
-  },
-  'GET /api/uploadVocab': (req: Request, res: Response) => {
-    res.json(
-      {
-        flag: true,
-        data: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png'
-      }
-    );
-  },
-  'GET /api/uploadLabel': (req: Request, res: Response) => {
-    res.json(
-      {
-        flag: true,
-        data: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png'
-      }
-    );
-  },
+  for (let i = 0; i < pageSize; i += 1) {
+    const index = (current - 1) * 10 + i;
+    tableListDataSource.push({
+      id: index,
+      modelName: `${index}name`,
+      modelFile: `${index}name`,
+      vocabFile: `${index}name`,
+      labelFile: `${index}name`,
+      mustTag: ``,
+      mustNotTag: ``,
+      onlyWord: `true`,
+      modelType: 0,
+    });
+  }
+  tableListDataSource.reverse();
+  return tableListDataSource;
+};
+
+const tableListDataSource = genList(1, 100);
+
+function getModels(req: Request, res: Response, u: string) {
+  let realUrl = u;
+  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
+    realUrl = req.url;
+  }
+  const {current = 1, pageSize = 10} = req.query;
+  const params = (parse(realUrl, true).query as unknown) as TableListParams;
 
+  const dataSource = [...tableListDataSource].slice((current - 1) * pageSize, current * pageSize);
+
+  const result = {
+    data: dataSource,
+    total: tableListDataSource.length,
+    success: true,
+    pageSize,
+    current: parseInt(`${params.currentPage}`, 10) || 1,
+  };
+
+  return res.json(result);
+}
+
+export default {
+  'GET /api/model': getModels,
 };

+ 5 - 8
src/pages/ModelList/components/UpdateForm.tsx

@@ -1,7 +1,5 @@
-import React from 'react';
+import React, {useEffect, useState} from 'react';
 import {Button, Form, Input, message, Modal, Radio, Upload} from 'antd';
-// @ts-ignore
-import {useSingleState} from 'nice-hooks';
 import {TableListItem} from '../data.d';
 import {UploadOutlined} from '@ant-design/icons';
 
@@ -25,7 +23,7 @@ const formLayout = {
 };
 
 const UpdateForm: React.FC<UpdateFormProps> = (props) => {
-  const [formVals, setFormVals] = useSingleState<FormValueType>(props.values);
+  const [formVals, setFormVals] = useState<FormValueType>(props.values);
 
   const [form] = Form.useForm();
 
@@ -38,12 +36,11 @@ const UpdateForm: React.FC<UpdateFormProps> = (props) => {
 
   const submit = async () => {
     const fieldsValue = await form.validateFields();
-    setFormVals({...fieldsValue},(newValue: FormValueType)=>{
-      handleUpdate(newValue);
-    });
+    const newValue = {...formVals, ...fieldsValue};
+    setFormVals(newValue);
+    handleUpdate(newValue);
   };
 
-
   const modelFileProps = {
     action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
     // @ts-ignore

+ 2 - 2
src/pages/ModelList/data.d.ts

@@ -1,6 +1,6 @@
 // 表单
 export interface TableListItem {
-  id: number;
+  id?: number;
   modelName: string;
   modelFile: string;
   vocabFile: string;
@@ -8,7 +8,7 @@ export interface TableListItem {
   mustTag: string;
   mustNotTag: string;
   onlyWord: string;
-  modelType: string;
+  modelType: number;
 }
 // 分页参数
 export interface TableListPagination {

+ 141 - 111
src/pages/ModelList/index.tsx

@@ -1,14 +1,11 @@
-import { DownOutlined, PlusOutlined } from '@ant-design/icons';
-import { Button, Divider, Dropdown, Menu, message } from 'antd';
-import React, { useState, useRef } from 'react';
-import { PageHeaderWrapper } from '@ant-design/pro-layout';
-import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
-import { SorterResult } from 'antd/es/table/interface';
-
-import CreateForm from './components/CreateForm';
-import UpdateForm, { FormValueType } from './components/UpdateForm';
-import { TableListItem } from './data.d';
-import { queryRule, updateRule, addRule, removeRule } from './service';
+import {PlusOutlined} from '@ant-design/icons';
+import {Button, Divider, message, Modal, Radio} from 'antd';
+import React, {useRef, useState} from 'react';
+import {PageHeaderWrapper} from '@ant-design/pro-layout';
+import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
+import {SorterResult} from 'antd/es/table/interface';
+import {TableListItem} from './data.d';
+import service from './service';
 
 /**
  * 添加节点
@@ -17,7 +14,7 @@ import { queryRule, updateRule, addRule, removeRule } from './service';
 const handleAdd = async (fields: TableListItem) => {
   const hide = message.loading('正在添加');
   try {
-    await addRule({ ...fields });
+    await service.addModel({...fields});
     hide();
     message.success('添加成功');
     return true;
@@ -32,12 +29,11 @@ const handleAdd = async (fields: TableListItem) => {
  * 更新节点
  * @param fields
  */
-const handleUpdate = async (fields: FormValueType) => {
+const handleUpdate = async (fields: TableListItem) => {
   const hide = message.loading('正在配置');
   try {
-    await updateRule(fields);
+    await service.updateModel(fields);
     hide();
-
     message.success('配置成功');
     return true;
   } catch (error) {
@@ -45,19 +41,17 @@ const handleUpdate = async (fields: FormValueType) => {
     message.error('配置失败请重试!');
     return false;
   }
+
 };
 
 /**
  *  删除节点
- * @param selectedRows
+ * @param fields
  */
-const handleRemove = async (selectedRows: TableListItem[]) => {
+const handleRemove = async (fields: TableListItem) => {
   const hide = message.loading('正在删除');
-  if (!selectedRows) return true;
   try {
-    await removeRule({
-      key: selectedRows.map((row) => row.id),
-    });
+    await service.removeModel(fields);
     hide();
     message.success('删除成功,即将刷新');
     return true;
@@ -68,53 +62,109 @@ const handleRemove = async (selectedRows: TableListItem[]) => {
   }
 };
 
+
 const TableList: React.FC<{}> = () => {
+
+
   const [sorter, setSorter] = useState<string>('');
-  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
-  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
+  const [modelVisible, setModalVisible] = useState<boolean>(false);
   const [formValues, setFormValues] = useState({});
   const actionRef = useRef<ActionType>();
   const columns: ProColumns<TableListItem>[] = [
     {
-      title: '规则名称',
-      dataIndex: 'name',
+      title: '模型类型',
+      dataIndex: 'modelType',
+      hideInSearch: true,
       rules: [
         {
           required: true,
-          message: '规则名称为必填项',
+          message: '模型类型为必填项',
         },
       ],
+      renderFormItem: () => {
+        return (
+          <Radio.Group>
+            <Radio value={0}>albert</Radio>
+            <Radio value={1}>Blstm</Radio>
+          </Radio.Group>
+        );
+      },
+      valueEnum: {
+        0: {text: 'albert'},
+        1: {text: 'Blstm'}
+      },
     },
     {
-      title: '描述',
-      dataIndex: 'desc',
-      valueType: 'textarea',
+      title: '模型名称',
+      dataIndex: 'modelName',
+      rules: [
+        {
+          required: true,
+          message: '模型名称为必填项',
+        },
+      ],
     },
     {
-      title: '服务调用次数',
-      dataIndex: 'callNo',
-      sorter: true,
-      hideInForm: true,
-      renderText: (val: string) => `${val} 万`,
+      title: '模型文件',
+      dataIndex: 'modelFile',
+      hideInSearch: true,
+      rules: [
+        {
+          required: true,
+          message: '模型名称为必填项',
+        },
+      ],
     },
     {
-      title: '状态',
-      dataIndex: 'status',
-      hideInForm: true,
-      valueEnum: {
-        0: { text: '关闭', status: 'Default' },
-        1: { text: '运行中', status: 'Processing' },
-        2: { text: '已上线', status: 'Success' },
-        3: { text: '异常', status: 'Error' },
-      },
+      title: '词向量文件',
+      dataIndex: 'vocabFile',
+      hideInSearch: true,
+      rules: [
+        {
+          required: true,
+          message: '词向量文件为必填项',
+        },
+      ],
     },
     {
-      title: '上次调度时间',
-      dataIndex: 'updatedAt',
-      sorter: true,
-      valueType: 'dateTime',
-      hideInForm: true,
+      title: '标签文件',
+      dataIndex: 'labelFile',
+      hideInSearch: true,
+      rules: [
+        {
+          required: true,
+          message: '标签文件为必填项',
+        },
+      ],
     },
+    {
+      title: '必包含',
+      dataIndex: 'mustTag',
+      hideInSearch: true,
+    },
+    {
+      title: '必不包含',
+      dataIndex: 'mustTag',
+      hideInSearch: true,
+    },
+    {
+      title: '纯文本',
+      dataIndex: 'onlyWord',
+      hideInSearch: true,
+      renderFormItem: () => {
+        return (
+          <Radio.Group>
+            <Radio value="true">是</Radio>
+            <Radio value="false">否</Radio>
+          </Radio.Group>
+        );
+      },
+      valueEnum: {
+        "true": {text: '是'},
+        "false": {text: '否'}
+      },
+    },
+
     {
       title: '操作',
       dataIndex: 'option',
@@ -123,80 +173,78 @@ const TableList: React.FC<{}> = () => {
         <>
           <a
             onClick={() => {
-              handleUpdateModalVisible(true);
+              setModalVisible(true);
               setFormValues(record);
               console.log(record)
             }}
           >
             配置
           </a>
-          <Divider type="vertical" />
-          <a href="">订阅警报</a>
+          <Divider type="vertical"/>
+          <a
+            onClick={() => {
+              handleRemove(record);
+              console.log(record)
+            }}
+          >
+            删除
+          </a>
         </>
       ),
     },
   ];
 
+  const [searchForm,setSearchForm] = useState({});
+
   return (
     <PageHeaderWrapper>
       <ProTable<TableListItem>
         headerTitle="查询表格"
         actionRef={actionRef}
-        rowKey="key"
+        rowKey="id"
         onChange={(_, _filter, _sorter) => {
           const sorterResult = _sorter as SorterResult<TableListItem>;
           if (sorterResult.field) {
             setSorter(`${sorterResult.field}_${sorterResult.order}`);
           }
         }}
+        pagination={{
+          defaultPageSize: 10
+        }}
         params={{
           sorter,
         }}
-        toolBarRender={(action, { selectedRows }) => [
-          <Button type="primary" onClick={() => handleModalVisible(true)}>
-            <PlusOutlined /> 新建
-          </Button>,
-          selectedRows && selectedRows.length > 0 && (
-            <Dropdown
-              overlay={
-                <Menu
-                  onClick={async (e) => {
-                    if (e.key === 'remove') {
-                      await handleRemove(selectedRows);
-                      action.reload();
-                    }
-                  }}
-                  selectedKeys={[]}
-                >
-                  <Menu.Item key="remove">批量删除</Menu.Item>
-                  <Menu.Item key="approval">批量审批</Menu.Item>
-                </Menu>
-              }
-            >
-              <Button>
-                批量操作 <DownOutlined />
-              </Button>
-            </Dropdown>
-          ),
+        /* eslint-disable */
+        toolBarRender={(action, {selectedRows}) => [
+          <Button type="primary" onClick={() => {
+            setModalVisible(true);
+            setFormValues({});
+          }}>
+            <PlusOutlined/> 新建
+          </Button>
         ]}
-        tableAlertRender={(selectedRowKeys, selectedRows) => (
-          <div>
-            已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
-            <span>
-              {/*服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万*/}
-            </span>
-          </div>
-        )}
-        request={(params) => queryRule(params)}
+        request={(params) => service.queryModel(params)}
         columns={columns}
         rowSelection={{}}
       />
-      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
+      <Modal
+        destroyOnClose
+        title={"id" in formValues ? "编辑" : "新建"}
+        visible={modelVisible}
+        onCancel={() => setModalVisible(false)}
+        footer={null}
+      >
         <ProTable<TableListItem, TableListItem>
           onSubmit={async (value) => {
-            const success = await handleAdd(value);
+            let success = false;
+            if (value.id) {
+              success = await handleAdd(value);
+            } else {
+              success = await handleUpdate(value);
+            }
+
             if (success) {
-              handleModalVisible(false);
+              setModalVisible(false);
               if (actionRef.current) {
                 actionRef.current.reload();
               }
@@ -206,28 +254,10 @@ const TableList: React.FC<{}> = () => {
           type="form"
           columns={columns}
           rowSelection={{}}
+          form={{initialValues: formValues}}
         />
-      </CreateForm>
-      {formValues && Object.keys(formValues).length ? (
-        <UpdateForm
-          onSubmit={async (value) => {
-            const success = await handleUpdate(value);
-            if (success) {
-              handleUpdateModalVisible(false);
-              setFormValues({});
-              if (actionRef.current) {
-                actionRef.current.reload();
-              }
-            }
-          }}
-          onCancel={() => {
-            handleUpdateModalVisible(false);
-            setFormValues({});
-          }}
-          updateModalVisible={updateModalVisible}
-          values={formValues}
-        />
-      ) : null}
+      </Modal>
+
     </PageHeaderWrapper>
   );
 };

+ 6 - 35
src/pages/ModelList/service.ts

@@ -1,38 +1,9 @@
-import request from '@/utils/request';
-import { TableListParams, TableListItem } from './data.d';
+import api from '@/utils/api';
 
-export async function queryRule(params?: TableListParams) {
-  return request('/api/rule', {
-    params,
-  });
+export default {
+  queryModel: api.get('/api/model'),
+  removeModel: api.post('/api/rule'),
+  addModel: api.post('/api/rule'),
+  updateModel: api.post('/api/rule')
 }
 
-export async function removeRule(params: { key: number[] }) {
-  return request('/api/rule', {
-    method: 'POST',
-    data: {
-      ...params,
-      method: 'delete',
-    },
-  });
-}
-
-export async function addRule(params: TableListItem) {
-  return request('/api/rule', {
-    method: 'POST',
-    data: {
-      ...params,
-      method: 'post',
-    },
-  });
-}
-
-export async function updateRule(params: TableListParams) {
-  return request('/api/rule', {
-    method: 'POST',
-    data: {
-      ...params,
-      method: 'update',
-    },
-  });
-}

+ 5 - 5
src/utils/api.ts

@@ -2,13 +2,13 @@ import request from '@/utils/request';
 
 export default {
 
-  get: url => params => request(url, {params,}),
+  get: (url: string) => (params: any) => request(url, {params,}),
 
-  post: url => params => request(url, {method: 'POST', data: {...params}}),
+  post: (url: string) => (params: any) => request(url, {method: 'POST', data: {...params}}),
 
-  postForm: url => params => request(url, {method: 'POST', data: {...params}, requestType: 'form'}),
+  postForm: (url: string) => (params: any) => request(url, {method: 'POST', data: {...params}, requestType: 'form'}),
 
-  delete: url => params => request(url, {method: 'POST', data: {...params, method: 'delete'}}),
+  delete: (url: string) => (params: any) => request(url, {method: 'POST', data: {...params, method: 'delete'}}),
 
-  put: url => params => request(url, {method: 'POST', data: {...params, method: 'put'}})
+  put: (url: string) => (params: any) => request(url, {method: 'POST', data: {...params, method: 'put'}})
 }

+ 0 - 66
src/utils/form-state.ts

@@ -1,66 +0,0 @@
-import React from "react";
-import produce from "immer"
-import set from "lodash/set";
-import has from "lodash/has";
-
-// eslint-disable-next-line consistent-return
-const enhancedReducer = (state, updateArg) => {
-  // check if the type of update argument is a callback function
-  if (updateArg.constructor === Function) {
-    return {...state, ...updateArg(state)};
-  }
-
-  // if the type of update argument is an object
-  if (updateArg.constructor === Object) {
-    // does the update object have _path and _value as it's keys
-    // if yes then use them to update deep object values
-    if (has(updateArg, "_path") && has(updateArg, "_value")) {
-      const {_path, _value} = updateArg;
-
-      return produce(state, draft => {
-        set(draft, _path, _value);
-      });
-    }
-    return {...state, ...updateArg};
-  }
-};
-
-const useFormState = initialState => {
-  const [state, updateState] = React.useReducer(enhancedReducer, initialState);
-
-  const updateForm = React.useCallback(({target: {value, name, type}}) => {
-    const updatePath = name.split(".");
-
-    // if the input is a checkbox then use callback function to update
-    // the toggle state based on previous state
-    if (type === "checkbox") {
-      updateState(prevState => ({
-        [name]: !prevState[name]
-      }));
-
-      return;
-    }
-
-    // if we have to update the root level nodes in the form
-    if (updatePath.length === 1) {
-      const [key] = updatePath;
-
-      updateState({
-        [key]: value
-      });
-    }
-
-    // if we have to update nested nodes in the form object
-    // use _path and _value to update them.
-    if (updatePath.length === 2) {
-      updateState({
-        _path: updatePath,
-        _value: value
-      });
-    }
-  }, []);
-
-  return [state, updateState,updateForm];
-};
-
-export default useFormState;