显示通过 API 返回的错误 - React Final Form

Showing errors returned via API - React Final Form

我正在尝试为每个无效字段显示通过 API 返回的内联错误。我正在关注 here 中的提交错误示例,内容如下:

const handleSubmit = async (values) => {
  let errors;

  await createProduct(values) // axios.post(...)
    .then((res) => ...)
    .catch((error) => {
      errors = error.response.data.errors;
      console.log(errors); // returns { title: ["can't be blank"] }
    });

  return errors; // returns { title: ["can't be blank"] }
}

那么我的表单如下所示:

   <Form onSubmit={handleSubmit}>
        {({
          submitError,
          handleSubmit,
          ...
        }) => (
          <BSForm onSubmit={handleSubmit}> // BSForm for boostrapform
            {submitError && (
              <div className="error">{submitError}</div> // not showing
            )}
            {console.log(submitError)} // returns 'undefined'
            <TextField
              name="title"
              ...
            />

如果我传递 {[FORM_ERROR]: 'error message'} 而不是返回 errors obj,我只能调用 submitError

我希望能够将这些 API 错误转发到相应字段的 meta: { error } 道具中,但我完全可以接受 submitError 包装 API错误。

发布后 30 秒找到解决方案。我错过了示例中的 meta: { submissionError } 道具。

所以我返回错误的方式似乎是正确的,唯一的区别是不用 meta.error && meta.touched 显示字段级错误,我必须像这样添加 meta.submitError

(meta.error || meta.submitError) && meta.touched; 

然后显示错误:

{(meta.error || meta.submitError) && meta.touched && (
  <span>{meta.error || meta.submitError}</span>
)}

以下是适用于我的用例的方法!在 submit handler 中,我只需要 解决 [=33] 发送的带有 错误对象 的承诺=],然后 React-final-form(RFF) 会将 error messages 向下传播到 各个字段状态 通过 meta.submitError.

这里要注意的另一件事是,得到解决的错误对象应该包含匹配 object keys or property names 作为发送到服务器的对象(即 form.values 中的字段名称应该匹配对象键当您收到 submit error 时,您 resolve 回来了)。我的 submit handler 最后看起来像这样:

 const submit = (values) => {
    const promise = 'some promise or api call';

    return new Promise(resolve => {
       promise(values))
        .then(response => {
          // ...do whatever
          resolve(true);
        })
        .catch(error =>{
             if (error.validationErrors) {
                resolve({ [FORM_ERROR]: error.validationErrors });
             } else {
                 //Depending on the shape of the error object from the server, destructure it or transform it so the keys match the field names in the form
                 //Example submissionErrors object would look like: {name: "Duplicate name detected", age: "Invalid age"}
                  const submissionErrors = {
                    ...error.data?.errors,
                    ...error.response?.data?.errors,
                   }; 
               // Then finally `resolve` the errorObject back to the form. 
              //This `resolve` is what makes RFF to update the fieldState of the affected fields with `meta.submitError`
             // You can then use `meta.submitError`, from `fieldState` of a given field, to display its `submission error`
               resolve({ ...submissionErrors});
           }
       });
    });
  };