【发布时间】:2018-10-18 14:45:39
【问题描述】:
有没有办法使用https://github.com/marmelab/react-admin 包执行服务器端表单验证?
这是 AdminCreate 组件的代码。它向api发送创建请求。如果一切正常,Api 会返回状态码 422 或状态码 200 的验证错误。
export class AdminCreate extends Component {
render() {
return <Create {...this.props}>
<SimpleForm>
<TextInput source="name" type="text" />
<TextInput source="email" type="email"/>
<TextInput source="password" type="password"/>
<TextInput source="password_confirmation" type="password"/>
<TextInput source="phone" type="tel"/>
</SimpleForm>
</Create>;
}
}
所以问题是,如何将每个字段的错误与从服务器发送的错误对象分开显示?这是错误对象的示例:
{
errors: {name: "The name is required", email: "The email is required"},
message: "invalid data"
}
提前谢谢你!
class SimpleForm extends Component {
handleSubmitWithRedirect = (redirect = this.props.redirect) =>
this.props.handleSubmit(data => {
dataProvider(CREATE, 'admins', { data: { ...data } }).catch(e => {
throw new SubmissionError(e.body.errors)
}).then(/* Here must be redirection logic i think */);
});
render() {
const {
basePath,
children,
classes = {},
className,
invalid,
pristine,
record,
resource,
submitOnEnter,
toolbar,
version,
...rest
} = this.props;
return (
<form
className={classnames('simple-form', className)}
{...sanitizeRestProps(rest)}
>
<div className={classes.form} key={version}>
{Children.map(children, input => (
<FormInput
basePath={basePath}
input={input}
record={record}
resource={resource}
/>
))}
</div>
{toolbar &&
React.cloneElement(toolbar, {
handleSubmitWithRedirect: this.handleSubmitWithRedirect,
invalid,
pristine,
submitOnEnter,
})}
</form>
);
}
}
现在我有以下代码,它显示验证错误。但问题是,成功后我无法执行重定向。有什么想法吗?
【问题讨论】:
-
我也在寻找一种方法来做到这一点。当我找到它时会回来的。
-
我将不胜感激
-
如果我没看错,您的解决方案是创建一个自定义
<SimpleForm>,直接使用 dataProvider 来捕获错误并显示它? -
我找到了迄今为止最好的解决方案:stackoverflow.com/a/54697878/2862728
-
@Rad80 是的,这太难了!我会尽快上传到这里。
标签: javascript reactjs react-admin