验证操作
Actions with validation
React admin 在edit/create 页面中提供操作供我们使用,这很好。但是,简单表单是子组件,因此操作不受简单表单的控制。如果我想在使用 fetch 发送到服务器之前验证表单数据,我该如何触发验证?
https://github.com/marmelab/react-admin/blob/master/docs/Actions.md
谢谢!
您可以再创建一个 class 处理程序,在该传递记录中您可以 return 错误或在没有错误的情况下为真,然后您可以调用 fetch。
// in src/comments/ApproveButton.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import FlatButton from '@material-ui/core/FlatButton';
import { showNotification } from 'react-admin';
import { push } from 'react-router-redux';
class ApproveButton extends Component {
handleValidate(data) {
const op = // validation logic goes here
return op;
}
handleClick = () => {
const { push, record, showNotification } = this.props;
const errors = handleValidate(record);
if(errors) {
// show errors in form
return;
}
const updatedRecord = { ...record, is_approved: true };
fetch(`/comments/${record.id}`, { method: 'PUT', body: updatedRecord })
.then(() => {
showNotification('Comment approved');
push('/comments');
})
.catch((e) => {
console.error(e);
showNotification('Error: comment not approved', 'warning')
});
}
render() {
return <FlatButton label="Approve" onClick={this.handleClick} />;
}
}
ApproveButton.propTypes = {
push: PropTypes.func,
record: PropTypes.object,
showNotification: PropTypes.func,
};
export default connect(null, {
showNotification,
push,
})(ApproveButton);
React admin 在edit/create 页面中提供操作供我们使用,这很好。但是,简单表单是子组件,因此操作不受简单表单的控制。如果我想在使用 fetch 发送到服务器之前验证表单数据,我该如何触发验证? https://github.com/marmelab/react-admin/blob/master/docs/Actions.md
谢谢!
您可以再创建一个 class 处理程序,在该传递记录中您可以 return 错误或在没有错误的情况下为真,然后您可以调用 fetch。
// in src/comments/ApproveButton.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import FlatButton from '@material-ui/core/FlatButton';
import { showNotification } from 'react-admin';
import { push } from 'react-router-redux';
class ApproveButton extends Component {
handleValidate(data) {
const op = // validation logic goes here
return op;
}
handleClick = () => {
const { push, record, showNotification } = this.props;
const errors = handleValidate(record);
if(errors) {
// show errors in form
return;
}
const updatedRecord = { ...record, is_approved: true };
fetch(`/comments/${record.id}`, { method: 'PUT', body: updatedRecord })
.then(() => {
showNotification('Comment approved');
push('/comments');
})
.catch((e) => {
console.error(e);
showNotification('Error: comment not approved', 'warning')
});
}
render() {
return <FlatButton label="Approve" onClick={this.handleClick} />;
}
}
ApproveButton.propTypes = {
push: PropTypes.func,
record: PropTypes.object,
showNotification: PropTypes.func,
};
export default connect(null, {
showNotification,
push,
})(ApproveButton);