react antd不在form表单中提交表单数据,而是点查询按钮时才将form表单数据和其他查询条件一起触发一次查询,避免重复触发请求

子组件:

javascript 复制代码
import React, { useRef } from 'react';
import { Form, Input } from 'antd';

const FormComponent = ({ formRef }) => {
  return (
    <Form ref={formRef} layout="vertical">
      <Form.Item
        name="username"
        label="Username"
        rules={[
          { required: true, message: 'Please input your username!' },
          { min: 3, message: 'Username must be at least 3 characters long' }
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="email"
        label="Email"
        rules={[
          { required: true, message: 'Please input your email!' },
          { type: 'email', message: 'The input is not valid E-mail!' }
        ]}
      >
        <Input />
      </Form.Item>
    </Form>
  );
};

export default FormComponent;

父组件:

javascript 复制代码
import React, { useState, useEffect, useRef } from 'react';
import { message, Button, Select } from 'antd';
import FormComponent from './FormComponent'; // 假设FormComponent在同一目录下

const ParentComponent = () => {
  const [otherQueryParams, setOtherQueryParams] = useState({
    status: 'active',
    role: 'admin'
  });
  const [loading, setLoading] = useState(false);
  const formRef = useRef();

  // 模拟API请求
  const fetchData = async (queryData) => {
    try {
      setLoading(true);
      // 模拟异步请求
      await new Promise((resolve) => setTimeout(resolve, 1000));
      console.log('Data fetched with query:', queryData);
      message.success('Data fetched successfully');
    } catch (error) {
      console.error('Error fetching data:', error);
      message.error('Failed to fetch data');
    } finally {
      setLoading(false);
    }
  };

  // 处理查询按钮点击事件
  const handleQuery = async () => {
    if (!formRef.current) return;

    try {
      const formData = await formRef.current.validateFields();
      const queryData = { ...formData, ...otherQueryParams };
      fetchData(queryData);
    } catch (errorInfo) {
      console.error('Failed to validate form:', errorInfo);
      message.error('Please check the form fields and try again.');
    }
  };

  return (
    <div>
      <h2>Parent Component</h2>
      <FormComponent formRef={formRef} />
      <div style={{ marginTop: '10px' }}>
        <label>Status:</label>
        <Select
          value={otherQueryParams.status}
          onChange={(value) => setOtherQueryParams({ ...otherQueryParams, status: value })}
          style={{ width: 120 }}
        >
          <Select.Option value="active">Active</Select.Option>
          <Select.Option value="inactive">Inactive</Select.Option>
        </Select>
      </div>
      <div style={{ marginTop: '10px' }}>
        <label>Role:</label>
        <Select
          value={otherQueryParams.role}
          onChange={(value) => setOtherQueryParams({ ...otherQueryParams, role: value })}
          style={{ width: 120 }}
        >
          <Select.Option value="admin">Admin</Select.Option>
          <Select.Option value="user">User</Select.Option>
        </Select>
      </div>
      <Button type="primary" onClick={handleQuery} loading={loading} style={{ marginTop: '10px' }}>
        Query
      </Button>
      {loading && <p>Loading...</p>}
    </div>
  );
};

export default ParentComponent;

也可以采用useEffect依赖项触发请求,在useEffect中判断form表单填充是否有内容,有内容时限制要传的表单参数state对象为''时不触发查询,同时判断当前表单填充内容与要传的表单参数state对象是否相等,相等时再触发查询。

相关推荐
NiceCloud喜云4 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby5 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing5 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩5 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车5 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思6 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫8 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。9 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星9 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒9 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端