将history.block与异步函数/callback/async/await一起使用

mcc*_*osa 5 async-await reactjs react-router react-router-dom formik

我在路线中有一个表单,如果存在任何验证错误,则不应允许用户导航到另一条路线。如果没有验证错误,则允许导航到另一条路线。

下面是我当前的代码,该onBlock函数不起作用,因为要提交然后验证表单的函数是异步的,因此该函数不起作用。

表单组件.js

import React, { useState, useEffect, useRef } from "react";
import { FieldArray } from "formik";
import { useHistory } from "react-router-dom";
import * as Yup from "yup";
import Form from "./Form";
import TextInput from "./TextInput";

const FormComponent = () => {
  const history = useHistory();
  const [initialValues, setInitialValues] = useState();
  const [isSubmitted, setIsSubmitted] = useState(false);
  const block = useRef();

  const formRef = useRef(null);

  const onFormSubmit = async (values) => {
    setIsSubmitted(true);
  };

  const validationSchema = () => {
    const schema = {
      test: Yup.string().required("Input is Required")
    };
    return Yup.object(schema);
  };

  const onBlock = () => {
    const { submitForm, validateForm } = formRef?.current || {};
    // submit form first
    submitForm()
      .then(() => {
        // then validate form
        validateForm()
          .then(() => {
            // if form is valid - should navigate to route
            // if form is not valid - should remain on current route
            return formRef?.current.isValid;
          })
          .catch(() => false);
      })
      .catch(() => false);
  };

  const redirectToPage = () => {
    history.push("/other-page");
  };

  useEffect(() => {
    block.current = history.block(onBlock);

    return () => {
      block.current && block.current();
    };
  });

  useEffect(() => {
    if (isSubmitted) redirectToPage();
  }, [isSubmitted]);

  useEffect(() => {
    setInitialValues({
      test: ""
    });
  }, []);

  return initialValues ? (
    <Form
      initialValues={initialValues}
      onSubmit={onFormSubmit}
      formRef={formRef}
      validationSchema={validationSchema}
    >
      <FieldArray
        name="formDetails"
        render={(arrayHelpers) =>
          arrayHelpers && arrayHelpers.form && arrayHelpers.form.values
            ? (() => {
                const { form } = arrayHelpers;
                formRef.current = form;
                return (
                  <>
                    <TextInput name="test" />
                    <button type="submit">Submit</button>
                  </>
                );
              })()
            : null
        }
      />
    </Form>
  ) : null;
};

export default FormComponent;
Run Code Online (Sandbox Code Playgroud)

如果用户尝试在输入中没有任何值的情况下提交表单,我希望这onBlock会返回false到块导航。但这似乎不起作用。然而,只需false在函数中返回即可。onBlock所以看起来该history.block函数不接受任何回调。我也尝试将其转换为async函数和await&函数,但仍然没有乐趣。有没有解决的办法?任何帮助将不胜感激。submitFormvalidateForm

这是CodeSandbox的示例。

Jon*_*eal 10

history.block函数接受提示回调,您可以使用该回调来提示用户或执行其他操作以响应页面被阻止。要阻止该页面,您只需在此处history.block()调用更多信息。

当您尝试提交表单时,formik 表单将被验证,如果成功验证,则将继续提交表单,此时onSubmit回调将被调用。因此,如果您想在出现验证错误时阻止页面,您可以使用 formik 上下文来订阅验证isValid,并且每当验证错误时都会阻止该页面。

const useIsValidBlockedPage = () => {
  const history = useHistory();
  const { isValid } = useFormikContext();

  useEffect(() => {
    const unblock = history.block(({ pathname }) => {
      // if is valid we can allow the navigation
      if (isValid) {
        // we can now unblock
        unblock();
        // proceed with the blocked navigation
        history.push(pathname);
      }
      // prevent navigation
      return false;
    });

    // just in case theres an unmount we can unblock if it exists
    return unblock;
  }, [isValid, history]);
};
Run Code Online (Sandbox Code Playgroud)

这是根据您的代码改编的代码沙箱。我删除了一些不需要的组件。

另一种解决方案是手动验证所有页面转换,并自行选择何时允许转换,在这种情况下,如果validateForm不返回错误,则允许转换。

// blocks page transitions if the form is not valid
const useFormBlockedPage = () => {
  const history = useHistory();
  const { validateForm } = useFormikContext();

  useEffect(() => {
    const unblock = history.block(({ pathname }) => {
     // check if the form is valid
      validateForm().then((errors) => {
        // if there are no errors this form is valid
        if (Object.keys(errors).length === 0) {
          // Unblock the navigation.
          unblock();
          // retry the pagination
          history.push(pathname);
        }
      });
      // prevent navigation
      return false;
    });
    return unblock;
  }, [history, validateForm]);
};
Run Code Online (Sandbox Code Playgroud)

以及这里的代码和框