useTable:
import React, { useState, useEffect } from 'react';
import axios from '@common/js/axios';
import qs from 'qs'
let searchData = {}
function useTable(url, ajaxData = {}) {
const [dataList, setDataList] = useState([]);
const [resData, setResData] = useState([]);
const [pagination, setPag] = useState({
pageSize: ajaxData.pageSize || 15,
current: 1,
showQuickJumper: true,
showSizeChanger: false,
showTotal: (total) => (
<span>
共<span className="text-warning">{total}</span>条
</span>
),
onChange: (current = 1) => {
setPagination({current})
}
});
const [loading, setLoading] = useState(false);
const [responseData, setResponseData] = useState({})
const getList = function({searchParam, paginationParam={}, config = {}}={}){
setLoading(true);
let isSearch = typeof searchParam === 'object'
let isCurrent = typeof paginationParam.current !== 'undefined'
let param = isSearch ? searchParam : searchData
if (isSearch) {
searchData = searchParam;
}
axios
.post(config?.url ? config.url : url, qs.stringify({
pageSize: 15,
curPage: isCurrent ? paginationParam.current - 1 : pagination.current - 1,
...ajaxData,
...param,
}))
.then((res) => {
if (res.flag === 1) {
setDataList(res.data.dataList);
setResData(res.data);
setPag({
...pagination,
current: res.data.curPage + 1,
total: res.data.totalRows
});
setLoading(false);
setResponseData(res.data);
}
});
}
useEffect(() => {
getList()
}, []);
const setSearchData = function(searchParam, paginationParam, config){
getList({searchParam, paginationParam, config})
}
const setPagination = function(paginationParam){
getList({paginationParam})
}
return {
dataList,
resData,
setDataList,
pagination,
loading,
setLoading,
searchData,
setSearchData,
responseData,
};
}
export default useTable;
使用:
// 调用
const { dataList, loading, pagination, searchData, setSearchData } = useTable(
'/list.json',
{}
)
// 搜索
const handleSearch = (data) => {
setSearchData(data, {current: 1})
}
// 重置
const handleClear = () => {
form.resetFields()
setSearchData({}, {current: 1})
}
return (
<>
<Table
loading={loading}
columns={columns}
dataSource={dataList}
rowKey="id"
pagination={pagination}
/>
{/* 新增客户 */}
{
addCustomerVisible &&
<AddCustomer
visible={addCustomerVisible}
onOk={() => {
setAddCustomerVisible(false)
setSearchData({}, {current: 1})
}}
onCancel={() => { setAddCustomerVisible(false) }}
/>
}
</>
)