reactjs - 如何在 React 中添加对状态码 400 的验证

我正在尝试编辑一个软件程序,该程序需要验证“未捕获( promise )错误:请求失败,状态代码为 400”错误

原因是用户试图在表上创建相同的唯一数据。这就是它获得状态代码 400 的原因。

现在,我想为状态代码 400 设置一个错误处理程序,并将在文本字段中返回一个字符串,说明“重复输入”

这是我当前的验证。

    import * as Yup from "yup";

const InvoiceValidationSchema = Yup.object().shape({
  customer: Yup.object()
    .required("Customer is required."),
  invoiceDate: Yup.string()
    .required("Invoice Date is required"),
  dueDate: Yup.string()
    .required("Due Date is required."),
  invoiceNumber: Yup.string()
    .required("Invoice Number is required"),
  invoiceLines: Yup.array()
    .of(
      Yup.object().shape({
        product: Yup.object().required("Required"),
        quantity: Yup.number().required("Required.").min(1, "Quantity cannot be zero."),
        // price: Yup.number().required("Required.").min(1, "Quantity cannot be zero.").typeError("")
      })
    ).required("Required")
});

export default InvoiceValidationSchema;

我希望有人能帮助我。谢谢

这是表格

<Formik
    validationSchema={InvoiceValidationSchema}
    initialValues={invoiceCrud}
    onSubmit={(values, action) => {

        const invoiceLines = values.invoiceLines.map(invoiceLine => {
            return {
                ...invoiceLine,
                product: invoiceLine.product,
                price: invoiceLine.price,
                quantity: invoiceLine.quantity,
                totalAmount: invoiceLine.quantity * invoiceLine.price,
                averagePurchasePrice: invoiceLine.product.averagePurchasePrice
            }
        })

        const subTotal = invoiceLines.reduce((sum, line) => {
            return sum + line.totalAmount;
        },0)

        const totalExpense = invoiceLines.reduce((sum, line) => {
            return sum + (line.product.averagePurchasePrice * line.quantity);
        },0)

        const totalAdjustment = 0;
        const netTotal = subTotal - totalAdjustment;

        const totalDueAmount = subTotal - values.subTotal + values.totalDueAmount;


        const invoice ={
            ...values,
            invoiceLines,
            subTotal,
            totalAdjustment,
            netTotal,
            totalExpense,
            totalDueAmount
        }

        if(values.invoiceLines[0].price > 0 && values.invoiceLines[0].quantity > 0){
            submit(invoice);
            setTimeout(() => {
                action.setSubmitting(false);
            }, 1000);
        }else{
            setIsZero(true)
            action.setSubmitting(false)
        }
    }}
    render={
        ({ values, errors, touched, setFieldValue, isSubmitting }) => (
             <Form>
                 <div className="box-body" id="invoice-crud">
                     <div className="row">
                         <div className="col-lg-3 col-md-6 col-sm-12">
                         {errors.invoiceLines ? setIsProductSelected(false) : null}
                         {errors.customer ? setCustomerClass("btn btn-default dropdown-toggle transaction-form__account has-error")
                             : setCustomerClass("btn btn-default dropdown-toggle transaction-form__account")}
                             <DropdownWithSearch
                                 property={
                                     {
                                         title: "Customer",
                                         buttonClass: CustomerClass,
                                         buttonLabel: values.customer ? values.customer.partnerName : "Select Customer",
                                         newButtonLabel: "Customer",
                                         showRemove: values.customer,
                                         modalSelector: "#partner-form"
                                     }
                                 }
                                 option={{
                                     list: partnerDetails.list,
                                     total: partnerDetails.total,
                                     currentPage: partnerDetails.currentPage,
                                     pageSize: partnerDetails.pageSize,
                                     load: changePartnerPage,
                                     display: (element) => element.partnerName,
                                     onClick: (element) => {
                                         setFieldValue("customer", element)
                                     },
                                     removeSelected: () => {
                                         setFieldValue("customer", null)
                                     },
                                     search: (search) => {
                                       dropdownSearch(search, "partner")
                                     }
                                 }}
                             />{errors.customer ? <span className="errorMessage">Please select a customer</span> : null}
                         </div>
                         <FormRow validation={{errors: errors, touched: touched}} field={invoiceNumber}/>
             </Form>
        )}
</Formik>

最佳答案

问题似乎与 Formik 和处理后端错误有关,而不是其他任何问题。

您可以在 this github issue 中查看如何在 formik 中手动设置后端错误.

特别是 this sandbox ,由用户 @t-nunes 在 github 中发布。

如果发出请求的函数是以新的 async/await 风格编写的,您可能会在 try/catch block 中处理错误,并且对于旧的 .then.catch 样式,只要服务器返回错误代码,您就可以使用 .catch 回调。

https://stackoverflow.com/questions/63231415/

相关文章:

google-api - Google Calendar API 在单个批处理请求中返回 403 R

python - 如何使用 Elasticsearch-dsl 在 Django 中进行并行测试?

angular - 在 Angular 10 中将 HTML 转换为 PDF

php - 使用 Laravel 的 Eloquent 将数据发送到数据库的问题

amazon-web-services - ECS 服务的两个或多个实例之间的通信

reactjs - 在 Jest 中测试 Axios

firebase - 如何将复杂的 Firestore 查询卸载到 Firebase Cloud F

python - Django 信号卡在循环中

python-3.x - 无论如何,您是否可以检查 Azure CLI 在后台执行哪些 API 调用

laravel - 如何在 Laravel 中显示带有法语符号的验证消息?