前言:使用url存储参数是一种非常有效的方式,当用户需要刷新浏览器之后之前的搜索标志依然存在,极大程度便捷了用户操作,当一个页面有很多表单时,就会很充分展现出它的优势。
import React, { useEffect, useRef } from "react";
import { ActionType, ProColumns, ProFormInstance, ProTable } from "@ant-design/pro-components";
import { NumberParam, QueryParamConfig, StringParam, useQueryParams, withDefault } from "use-query-params";
export default function Index() {
const actionRef = useRef<ActionType>();
const formRef = useRef<ProFormInstance>();
const [query, setQuery] = useQueryParams({
goodsName: StringParam as QueryParamConfig<string|undefined>,
type: StringParam as QueryParamConfig<StockListPageDTOTypeEnum|undefined>,
});
useEffect(() => {
formRef?.current?.setFieldsValue({
goodsName: query?.goodsName,
type: query?.type,
});
},[
query?.goodsName,
query?.type,
]);
const handleQuery = (params: Omit<InventoryApiStockPageListRequest, 'page'> & { current: number }) => {
setQuery({
goodsName: params.goodsName,
type: params.type,
});
};
const handleReset = () => {
actionRef.current?.reset?.();
};
return (
<ProTable
actionRef={actionRef}
formRef={formRef}
columns={columns}
cardBordered
rowKey="id"
search={{
labelWidth: 'auto',
}}
request={handleQuery}
onReset={handleReset}
form={{
initialValues: {
goodsName: query.goodsName,
type: query.type,
},
submitter: {
render:(props, doms) => [...doms.reverse()]
}
}}
options={false}
dataSource={[]}
/>
)
}
- 点击搜索时触发
handleQuery
从而setQuery
此时url
上会有此时的search
参数 - 刷新页面后
2.1使用useEffect设置将url中的参数放入表单
2.2 使用ProTable的form initialValues初始化给表单useEffect(() => { formRef?.current?.setFieldsValue({ goodsName: query?.goodsName, type: query?.type, }); },[ query?.goodsName, query?.type, ]);
2.3 有的2.2这一步之后handleQuery的参数才是最新的,这一步的操作是将参数放入form={{ initialValues: { goodsName: query.goodsName, type: query.type, }, }}
url
中const handleQuery = (params) => { setQuery({ goodsName: params.goodsName, type: params.type, }); };
至此结束 再会!