React使用ProTable时点击搜索将表单同步到url,刷新页面之后读取url参数同步到ProTable的表单输入框

前言:使用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={[]}
    />
  )
}
  1. 点击搜索时触发handleQuery 从而setQuery此时url上会有此时的search参数
  2. 刷新页面后
    2.1使用useEffect设置将url中的参数放入表单
    useEffect(() => {
      formRef?.current?.setFieldsValue({
        goodsName: query?.goodsName,
        type: query?.type,
      });
    },[
      query?.goodsName,
      query?.type,
    ]);
    
    2.2 使用ProTable的form initialValues初始化给表单
    form={{
      initialValues: {
        goodsName: query.goodsName,
        type: query.type,
      },
    }}
    
    2.3 有的2.2这一步之后handleQuery的参数才是最新的,这一步的操作是将参数放入url
    const handleQuery = (params) => {
      setQuery({
        goodsName: params.goodsName,
        type: params.type,
      });
    };
    

至此结束 再会!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容