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

相关推荐
像风一样自由20201 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
伍哥的传说2 小时前
React 各颜色转换方法、颜色值换算工具HEX、RGB/RGBA、HSL/HSLA、HSV、CMYK
深度学习·神经网络·react.js
aiprtem2 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术2 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing2 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止3 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall3 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴3 小时前
简单入门Python装饰器
前端·python
袁煦丞4 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作