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

相关推荐
前端九哥2 分钟前
🚫循环里写return,浏览器当场沉默!
前端·javascript
亲爱的马哥9 分钟前
填鸭表单!开箱即用的开源问卷调查系统!
java·前端·低代码·产品经理
米诺zuo18 分钟前
nextjs文件路由、路由组
前端·next.js
加个鸡腿儿19 分钟前
锚点跳转-附带CSS样式 & 阻止页面刷新技术方案
前端·javascript·css
一念一花一世界29 分钟前
Arbess从初级到进阶(4) - 使用Arbess+GitLab实现React.js 项目自动化部署
react.js·ci/cd·gitlab·arbess
程序猿_极客37 分钟前
【期末网页设计作业】HTML+CSS+JS 美食分享主题网站设计与实现(附源码)
javascript·css·html
dragon72538 分钟前
FutureProvider会刷新两次的问题研究
前端·flutter
天蓝色的鱼鱼1 小时前
Next.js路由全解析:Pages Router 与 App Router,你选对了吗?
前端·next.js
xun_xing1 小时前
基于Nextjs15的学习手记
前端·javascript·react.js
有意义1 小时前
Vibe Coding:人机共生时代的开发革命 —— 从概念到 Chrome 扩展实战
前端·ai编程·vibecoding