7

表单提交失败后如何显示验证消息?API 请求返回 HTTP 400 'application/problem+json' 响应,并包含违规作为带有字段路径的列表。

https://www.rfc-editor.org/rfc/rfc7807#section-3

{
   "type": "https://example.net/validation-error",
   "title": "Your request parameters didn't validate.",
   "invalid-params": [ 
      {
         "name": "age",
         "reason": "must be a positive integer"
      },
      {
         "name": "color",
         "reason": "must be 'green', 'red' or 'blue'"
      }
   ]
}
4

1 回答 1

7

我有适合你的解决方案,我建议使用 Saga 和 HttpError。

首先,从我们的 dataProvider 我们需要抛出HttpError这样的:

...
import {HttpError} from 'react-admin';
...
...

// Make the request with fetch/axios whatever you prefer and catch the error:
// message - the message that will appear in the alert notification popup
// status - the status code
// errors - the errors in key => value format, example in comment below
return fetchClient.request(config).then((response) => {
      return convertHTTPResponse(response, type, resource, params);
    }).catch(function (error) {
      throw new HttpError(error.response.data.message, error.response.status, error.response.data.errors);
    });

然后像这样创建传奇:

import {CRUD_CREATE_FAILURE} from "react-admin";
import {stopSubmit} from 'redux-form';
import {put, takeEvery} from "redux-saga/effects";

export default function* errorSagas() {
  yield takeEvery(CRUD_CREATE_FAILURE, crudCreateFailure);
}

export function* crudCreateFailure(action) {
  var json = action.payload;
  // json structure looks like this:
  // {
  //     username: "This username is already taken",
  //     age: "Your age must be above 18 years old"
  // }
  yield put(stopSubmit('record-form', json));
}

请确保错误(json)的格式与上例相同!

然后将 saga 插入组件中:

import errorSagas from './sagas/errorSagas';
...
...

<Admin
        customSagas={[ errorSagas ]}
        loginPage={LoginPage}
        authProvider={authProvider}
        dataProvider={dataProvider}
      >

繁荣!有用 在此处输入图像描述

祝你好运!

于 2019-02-14T19:36:07.583 回答