Bootstrap

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

子组件:

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;

父组件:

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

;