Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useAntdTable在submit的时候,固定分页条件 #2635

Open
freesaber opened this issue Aug 28, 2024 · 2 comments
Open

useAntdTable在submit的时候,固定分页条件 #2635

freesaber opened this issue Aug 28, 2024 · 2 comments

Comments

@freesaber
Copy link

封装了一个组件proTable

import { useAntdTable } from 'ahooks';
...
  const [form] = Form.useForm();
  const { tableProps, search: { submit, reset } } = useAntdTable(request, {
    defaultPageSize,
    form
  });

  if(tableRef){
    useImperativeHandle(tableRef, () => {
      return {
        submit: () => {
          submit();
        
        },
        reset: () => {
          reset();
        }
      }
    });
  }
...

<Table<T>
          {...tableProps}
          scroll={{ x: true, ...scroll }}
          pagination={false}
          rowKey={rowKey}
          size="middle"
          columns={columns}
          rowSelection={
            rowSelection
              ? {
                  type: selectionType,
                  selectedRowKeys: selectedKeys,
                  onChange: handleRowSelectionChange,
                }
              : undefined
          }
        />

...
<Pagination
          showQuickJumper
          showTotal={(total) => `总共  ${total} 条`}
          pageSizeOptions={Array.from({ length: 10 }, (_, i) => (i + 1) * 10).map(String)}
          {...tableProps.pagination}
          onChange={(page, pageSize) => tableProps.onChange({current: page, pageSize})}
        />
...

使用proTable

 const columns: TableColumnsType<Auth.Person> = [
{
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      width: 250,
      render: (_, record) => (
        <Space.Compact block>
        </AuthButton>
          {
            record.status === 0 ?
            <Popconfirm
              title="确定启用该员工吗?"
              onConfirm={() => handleEnable(record)}
            >
              <AuthButton size="small" type="link" auth={authConstants.PERSON_ENABLE}>启用</AuthButton>
            </Popconfirm>
            :<Popconfirm
              title="确定禁用该员工吗?"
              onConfirm={() => handleEnable(record)}
            >
              <AuthButton size="small" type="link" auth={authConstants.PERSON_ENABLE}>禁用</AuthButton>
            </Popconfirm>
          }
    }
]

const getTableData = async ( params: TableParams, formData: FormData): Promise<{ total: number; list: Auth.Person[] }> => {
    const { current, pageSize, filters, sorter, extra } = params;

    const result = await getStorePersonEmployeeList(queryParams);

    return {
      total: result ? Number(result.totalCount) : 0,
      list: result ? result.list : [],
    };
}

...

  // 启用、禁用
  const handleEnable = async (record: Auth.Person) => {
 
    const status = record.status === 0 ? 1 : 0;
    const params = {
      id: record.employeeId,
      status
    };
    try {

      await updatePersonEmployeeStatus(params)
      if(status === 0 ){
        message.error(`禁用成功`);
      }else {
        message.success(`启用成功`);
      }
      proTableRef?.current?.submit();
    } catch {
    }
  }

...

ProTable<Auth.Person>
      tableRef={proTableRef}
      rowKey="employeeId"
      columns={columns}
      request={getTableData}
>

我的问题是,proTableRef?.current?.submit();最后是执行的useAntdTable的submit。这个submit导致,分页重新回到第一页。怎样让分页数量固定到当前页呢。

@freesaber
Copy link
Author

加了一个标记,通过onChange触发了,下面是proTable

  const [form] = Form.useForm();
  const { tableProps, search: { submit, reset } } = useAntdTable(request, {
    defaultPageSize,
    form
  });

  if(tableRef){
    useImperativeHandle(tableRef, () => {
      return {
        submit: (useCurrentPage = false) => {
          if (useCurrentPage) {
            tableProps.onChange(pagination);
          } else {
            submit()
          }
          setSelectedKeys([]);
          setSelectedRows([]);
        },
        reset: () => {
          reset();
          setSelectedKeys([]);
          setSelectedRows([]);
        }
      }
    });
  }

...
  // 缓存当前的分页信息
  const [pagination, setPagination] = useState({ current: 1, pageSize: defaultPageSize });
  const handleTableChange = (page:number, pageSize:number) => {
    setPagination({current: page, pageSize})
    tableProps.onChange({current: page, pageSize})
  }
...

<Form form={form}>
              <Col
                {...searchGrid}
                offset={fold && search.length > colNum - 1 ? undefined : notFoldOffset}
              >
                <Space align="baseline" style={{width: '100%', justifyContent: 'end', marginRight: 16}}>
                  <Button type="primary" onClick={() => {
                    setPagination({...pagination, current: 1})
                    submit();
                  }}>
                    查询
                  </Button>
                  <Button onClick={() => {
                    setPagination({current: 1, pageSize: defaultPageSize})
                    reset();
                    onReset && onReset();
                  }}>
                    重置
                  </Button>
                  {search.length > colNum - 1 && (
                    <a style={{ marginLeft: 8 }} onClick={() => setFold(!fold)}>
                      {fold ? '展开' : '收起'}
                      &nbsp;
                      <span>{fold ? <DownOutlined/> : <UpOutlined/>}</span>
                    </a>
                  )}
                </Space>
              </Col>
</Form>


...

        <Pagination
          showQuickJumper
          showTotal={(total) => `总共  ${total} 条`}
          pageSizeOptions={Array.from({ length: 10 }, (_, i) => (i + 1) * 10).map(String)}
          {...tableProps.pagination}
          onChange={(page, pageSize) => handleTableChange(page, pageSize)}
        />
...

外部掉用

  // 启用、禁用
  const handleEnable = async (record: Auth.Role) => {
    const params = {
      name: record.name,
      status: record.status === 0 ? 1 : 0
    };
    try {
      await updateRoleStatus(record.id, params)
      proTableRef?.current?.submit(true);
    } catch (error) {

    }
  }

@crazylxr
Copy link
Collaborator

emm,那你还有问题吗 @freesaber

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants