验证动作

时间:2018-10-29 04:36:40

标签: reactjs react-admin

最好让react admin为我们提供要在编辑/创建页面中使用的操作。但是,简单形式是子组件,因此操作不受该简单形式的控制。如果要在使用提取将数据发送到服务器之前验证表单数据,如何触发验证? https://github.com/marmelab/react-admin/blob/master/docs/Actions.md

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以再创建一个类处理程序,并在该传递记录中,在没有错误的情况下可以返回错误或true,然后可以调用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);
相关问题