antd中如何给form表单做数据的返显

在使用Ant-DesignUI库中的Form组件时,怎样在编辑页面时将之前保存过的数据返显在页面?
思路:
1、在componentDidMount生命周期中调用api获取后台数据;
2、通过form的setFieldsValue()方法将后台数据绑定到Form表单控件中。

注意:使用 getFieldsValue, getFieldValue, setFieldsValue 等时,应确保对应的 field 已经用 getFieldDecorator 注册过了。

页面展示如下:
在这里插入图片描述
实际代码如下:
index.jsx文件,

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Button, Row, Col, message, Card} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import styles from './index.less';
// 设置input框的label以及input框的占比
const formItemLayout = {
  labelCol: {span: 9},
  wrapperCol: {span: 15}
};
// 绑定全局state
@connect(state => {
  return {
    submitting:state.loading.models.getCompanyInfo,
    getCompanyInfo: state.getCompanyInfo
  }
})
// 通过Form.create()包装组件,获取form的api
@Form.create()
export default class extends PureComponent {
  //通过form.setFieldsValue将数据绑定到各个Form表单控件上,这里定义了返显的方法。
  setBaseInfo = (data) => {
    const { form } = this.props;
    Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      if (data[key]) {
        obj[key] = data[key] || null;
      }
      form.setFieldsValue(obj);
    });
  };

  componentDidMount() {
    const {
      dispatch,
      location: {
        query: { id },
        pathname,
      },
    } = this.props;
    const { setBaseInfo } = this;
    const isEdit = pathname.includes('edit');
    if (!isEdit) return;
    // 通过dispatch方法请求后台数据(dva数据管理)
    dispatch({
      type: 'getCompanyInfo/fetch',
      payload: {
        data: { id },
      },
      callBack(msg, status, data) {
        if (status === 200) {
          // 获取数据,调用返显方法
          setBaseInfo(data);
        } else {
          message.error(msg); 
        }
      }
    });
  }
  render() {
    const {
      dispatch,
      form: {
        getFieldDecorator,
        validateFields
      },
      location: {
        query: { id },
        pathname,
      },
      submitting,
    } = this.props;
    //因为新增功能和编辑功能调用的是同一个页面,所以需要根据pathname来判断一下我们对页面的操作是新增还是编辑
    const isEdit = pathname.includes('edit');
    // 保存数据时通过validateFields()进行页面Input控件的正则验证以及Input中value值的获取
    const onValidateForm = () => {
      const postUrl = isEdit ? 'updateCompanyInfo/fetch' : 'insertCompanyInfo/fetch';
      validateFields((err, fieldsValue) => {
        if (err) return;
        if (isEdit) {
          fieldsValue.id = id;
        }
        dispatch({
          type: postUrl,
          payload: {
            data: {
              ...fieldsValue,
            },
          },
          callBack( msg, status, data ) {
            if (status === 200) {
              // 保存数据成功后,进行路由跳转(umi的router)
              router.push({
                pathname: '/paramset/companyCtrl',
              });
            } else {
              message.error(msg);
            }
          },
        });
      });
    };

    return (
      <PageHeaderWrapper title={`${isEdit ? '编辑' : '新增'}签章信息`}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            <Form layout='horizontal' labelAlign='right'>
              <Card title='基本信息' style={{ marginBottom: 22 }}>
                <Row gutter={30}>
                  <Col md={8} lg={8}>
                    <Form.Item {...formItemLayout} label='公司ID'>
                      {getFieldDecorator('companyId', {
                        rules: [
                          {
                            required: true,
                            message: '请输入公司ID',
                          },
                        ]
                      })(
                        <Input minLength={4} maxLength={32} placeholder='请输入' />
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={8} lg={8}>
                    <Form.Item {...formItemLayout} label='公司名称'>
                      {getFieldDecorator('companyName', {
                        rules: [
                          {
                            required: true,
                            message: '请输入公司名称',
                          },
                        ],
                      })(
                        <Input maxLength={100} placeholder='请输入' />
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={8} lg={8}>
                    <Form.Item {...formItemLayout} label='联系电话'>
                      {getFieldDecorator('phone')(
                        <Input maxLength={12} placeholder='请输入' />
                      )}
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              <footer style={{ textAlign: 'center' }}>
                <Button type='default' style={{ marginRight: 75 }}>
                  <Link to={{ pathname: '/paramset/companyCtrl' }}>返回</Link>
                </Button>
                <Button type='primary' onClick={onValidateForm} loading={submitting}>
                  保存
                </Button>
              </footer>
            </Form>
          </div>
        </div>
      </PageHeaderWrapper>
    );
  }
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值