The reason

There is such a problem that the user clicks the verification button and then clicks OK to submit the form.

However, during the testing process, the form needs to be submitted after two validations are completed. If the verification fails, a message is displayed and cannot be submitted. That makes things complicated.

Analysis of the

Code analysis: Since the two validations in the diagram are written on different child components, determine that the submission form is a parent component. So I came up with the idea of the parent component calling the child component, and went to the official documentation to see how to use useImperativeHandle. The document

How to use
import { useState, useImperativeHandle ,useRef} from 'react';
// props子组件中需要接受ref
function ChildComp({ cRef }) {
    const [val, setVal] = useState();
    function rules(a) {
        setVal(a)
        console.log(a);
    }
    // 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
    useImperativeHandle(cRef, () => ({
        // changeVal 就是暴露给父组件的方法
        changeVal: (newVal) => {
            rules(newVal);
        }
    }));
    return (
        <div>{val}</div>
    )
}
export default function App() {
    const childRef = useRef();
    const updateChildState = () => {
        // changeVal就是子组件暴露给父组件的方法
        childRef.current.changeVal(99);
    }
    return (
        <>
            {/* 此处注意需要将childRef通过props属性从父组件中传给自己 cRef={childRef} */}
            <ChildComp cRef={childRef} />
            <button onClick={updateChildState}>触发子组件方法</button>
        </>
    )
}

Copy the code

Combined with demand

Now, if you need to verify that the form is wrong, you can’t submit it. At this point, you want to use a promise. You want to wrap the form’s validation method with a promise

function rules(a) { return new Promise((res, rej) => { request({ url: '/demo/api', needMask: true, data, success: () = > {res () message. Success (' successful check, no error ')}, fail: () = > {rej () message. Error (' validation failure ')}})})}Copy the code

Since there are two validations, you can commit only if both validations succeed, using promise.all([]), then the problem is solved

function submit(){ let PromiseRules = []; PromiseRules.push(childRef.current.childFun(data)); PromiseRules.push(childRef1.current.childFun(data)); Promise.all(PromiseRules) .then((res) => { request({ url: "/demo1/api", needMask: true, data: { data }, success: (res) => {message.success(" save successfully "); }, fail: (err) => { message.error(err); }}); }) .catch((err) => { console.log(err); }); }Copy the code