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对象是否相等,相等时再触发查询。

相关推荐
_山海32 分钟前
Bun入门指南
前端·javascript·后端
想睡懒觉38 分钟前
我用 CSS 3D 做了个星空隧道 Loading,没有 Three.js
前端
labixiong42 分钟前
transition 写在 CSS 变量上为什么不生效?给变量补张「类型身份证」
前端·css·html
YHL1 小时前
🧠 Agent 记忆进阶:总结压缩与向量检索 —— 从截断到 Milvus 长期记忆
前端·人工智能
YHL1 小时前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
用户921080262861 小时前
前端 Vue 专栏 05:从 Object.defineProperty 到 Proxy,彻底理解 Vue 响应式原理
前端
Fluxart.ai1 小时前
GPT Image 2.5 有使用次数限制吗?额度、并发、频率限制说明
服务器·前端·gpt
程序员海军2 小时前
AI 越来越强,为什么打工人反而越来越累、越来越内耗了?
前端·程序员·aigc
vx_Biye_Design2 小时前
springboot游泳馆系统93765-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·spring·课程设计