It seems that there is an issue with the code logic. The 'getFieldDecorator' method should be called outside of the 'renderContent' method, in the 'componentDidMount' lifecycle method. Additionally, the 'list' variable should be defined as a state variable in the constructor and updated using 'setState'. Here's an updated version of the code:

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Modal, Select, Row, Col } from 'antd';

const { Option } = Select;
const FormItem = Form.Item;

@Form.create()
@connect(({ filterBlock }) => ({  filterBlock,}))class UpdateForm extends PureComponent {  constructor(props) {    super(props);    this.state = {      visible: false,      formVals: props.record || {},      filterSelect: [],      keyId: '',      list: [{}], // Define list as a state variable    };

    this.formLayout = {      labelCol: { span: 4 },      wrapperCol: { span: 18 },    };

    this.formLayout1 = {      labelCol: { span: 10 },      wrapperCol: { span: 14 },    };
    this.formLayout2 = {      labelCol: { span: 6 },      wrapperCol: { span: 18 },    };  }

  componentDidMount() {    const { dispatch, form } = this.props;    const { formVals } = this.state;    if (formVals.key) {      dispatch({        type: 'filterBlock/fetchItemsList',        payload: formVals.key,        callback: res => {          if (res && res.status === 200) {            const centerData = res.data.map(item => {              return {                label: item,                value: `${item}`,              };            });            this.setState({ filterSelect: centerData });          }        },      });    }

    // Initialize 'list' form field value    form.setFieldsValue({      list: this.state.list,    });  }

  handleSave = () => {    const { form, okChange, index, record, filterList } = this.props;    const { formVals, keyId } = this.state;    form.validateFields((err, fieldsValue) => {      if (err) return;

      const arrData = fieldsValue.content.reduce((arr, next) => {        const typeList = next.type.map(type => {          return { type, name: next.name };        });        return arr.concat(typeList);      }, []);

      const nameValue = (filterList || []).find(item => item.id === keyId)?.title;
      const formItem = {        key: keyId || formVals?.key,        value: fieldsValue?.value || nameValue,        typeList: arrData,      };
      console.log(formItem, 80);
      okChange(formItem, index);
      this.handleVisible();    });  };

  handleVisible = (flag, record) => {    this.setState({      visible: !!flag,      formVals: record || {},    });  };

  // 添加  add = () => {    const { form } = this.props;    const { list } = this.state;    const nextList = [...list, {}]; // Update list state    this.setState({ list: nextList }, () => {      form.setFieldsValue({        list: this.state.list,      });    });  };

  // 删除  deleteRow = index => {    const { form } = this.props;    const { list } = this.state;    if (list.length === 1) {      return;    }    const nextList = list.filter((item, key) => key !== index); // Update list state    this.setState({ list: nextList }, () => {      form.setFieldsValue({        list: this.state.list,      });    });  };

  projectChange = keys => {    const { dispatch } = this.props;    const { filterSelect, keyId } = this.state;    dispatch({      type: 'filterBlock/fetchItemsList',      payload: keys,      callback: res => {        if (res && res.status === 200) {          const centerData = res.data.map(item => {            return {              label: item,              value: `${item}`,            };          });          this.setState({ filterSelect: centerData, keyId: keys });        }      },    });  };

  renderContent = formVals => {    const { filterSelect, list } = this.state;    const { formLayout, formLayout1, formLayout2 } = this.props;    const {      form: { getFieldDecorator, getFieldValue },      filterList,    } = this.props;

    const selectProps = {      placeholder: '请选择',      optionFilterProp: 'children',      style: {        width: '100%',      },      allowClear: true,      showSearch: true,    };

    return (      <Form>        <FormItem key='value' {...formLayout} label='筛选项'>          {getFieldDecorator('value', {            rules: [{ required: true, message: '请选择筛选项' }],            initialValue: formVals.value,          })(            <Select {...selectProps} onChange={value => this.projectChange(value)}>              {filterList?.length &&                filterList?.map(items => (                  <Option                    key={items.id}                    value={items.id}                    disabled={(this.props?.sourceData || []).find(item => item.key == items.id)}                  >                    {items.title}                  </Option>                ))}            </Select>          )}        </FormItem>
        {(list || []).map((item, index) => {          return (            <Row key={index}>              <Col span={10}>                <FormItem label={`筛选类${index + 1}`} {...formLayout1}>                  {getFieldDecorator(`content[${index}].type`, {                    rules: [                      {                        required: true,                        message: '请选择筛选类!',                      },                    ],                    initialValue: item.type?.split(','),                  })(                    <Select {...selectProps} mode='multiple'>                      {filterSelect.map(item1 => (                        <Option key={item1.label} value={item1.value}>                          {item1.label}                        </Option>                      ))}                    </Select>                  )}                </FormItem>              </Col>
              <Col span={10}>                <FormItem label='别称' {...formLayout2}>                  {getFieldDecorator(`content[${index}].name`, {                    initialValue: item.name,                    rules: [                      {                        required: true,                        message: '请输入别称',                      },                    ],                  })(<Input placeholder='请输入' />)}                </FormItem>              </Col>
              <Col span={4}>                <div                  style={{ width: '100%', height: '27px', marginTop: '10px', marginLeft: '10px' }}                >                  {index > 0 ? (                    <span                      style={{ color: '#1890FF', cursor: 'pointer' }}                      onClick={this.deleteRow.bind(this, index)}                    >                      删除                    </span>                  ) : null}                  {index === 0 ? (                    <span                      style={{ paddingRight: '12px', color: '#1890FF', cursor: 'pointer' }}                      onClick={this.add}                    >                      新增                    </span>                  ) : null}                </div>              </Col>            </Row>          );        })}      </Form>    );  };

  render() {    const { children, record } = this.props;    const { visible, formVals } = this.state;    return (      <>        {React.cloneElement(children, {          onClick: () => this.handleVisible(true, record),        })}        <Modal          width={800}          bodyStyle={{ padding: '15px 30px' }}          destroyOnClose          title={Object.keys(formVals).length > 0 ? '编辑' : '新建'}          visible={visible}          onOk={() => this.handleSave()}          onCancel={() => this.handleVisible()}          maskClosable={false}        >          {this.renderContent(formVals)}        </Modal>      </>    );  }  }UpdateForm.defaultProps = {  okChange: () => {},};
export default UpdateForm;```

By moving the 'getFieldDecorator' call to 'componentDidMount', the 'list' state will be properly initialized and updated when adding or deleting rows.

原文地址: https://www.cveoy.top/t/topic/qkZz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录