如何在一个字段数组中修复多个字段,并单击“添加更多”以打开单个字段数组?

时间:2019-03-26 07:38:09

标签: react-redux

我做了一份家庭作业。在Redux,老师已经更改了它,并要求以我不理解的其他方式进行操作。

这是以前分配的屏幕截图。

此屏幕快照是上一屏幕,根据此屏幕快照,我已完成流程:

1

代码如下:

index.js

import React, { Component } from 'react';
import { asyncConnect } from 'redux-connect';
import { connect } from 'react-redux';
import _ from 'lodash';
import { Page } from 'modules/App/components';
import ErrorToast from 'modules/Hrms/components/HrmsErrorToast';
import ToastHoc from 'components/ToastHoc';

import configurationActions, {
    selectAppParamsIdMap,
    selectAppParams,
} from 'modules/Configuration/store/actions/actions';

import EmployeeQualificationForm from './employeeQualification';

import EmployeeActions from '../../../store/actions/actions';

@asyncConnect([
    {
        promise: ({ store: { dispatch, getState } }) => {
            // Todo: Get this id from application parameter table
            // const state = getState();
            // let paramsArray = Object.values(state.configuration.appParams);
            // let medumId = paramsArray.find(function(element) {
            //   let object = element.name === "MEDM"? element.id : 1;
            //   return object.id;
            // });
            const state = getState();
            const idsMap = selectAppParamsIdMap(state);
            return Promise.all([
                dispatch(configurationActions.getAppParam(idsMap.INDU)),
                dispatch(configurationActions.getAppParam(idsMap.FUAR)),
                dispatch(configurationActions.getAppParam(idsMap.ROCA)),
                dispatch(configurationActions.getAppParam(idsMap.EMTY)),
                dispatch(configurationActions.getAppParam(idsMap.QUAL)),
                dispatch(configurationActions.getAppParam(idsMap.NATI)),
                dispatch(configurationActions.getAppParam(idsMap.GEND)),
                dispatch(configurationActions.getAppParam(idsMap.NATY)),
                dispatch(configurationActions.getAppParam(idsMap.MAST)),
                dispatch(configurationActions.getAppParam(idsMap.RELI)),
                dispatch(configurationActions.getAppParam(idsMap.SOCL)),
                dispatch(configurationActions.getAppParam(idsMap.MEDM)),
                dispatch(EmployeeActions.loadApplicationParams(4)),
            ]);
        },
    },
])
@connect(
    state => ({
        appParams: selectAppParams(state),
        contextId:
            state.auth.user.appFeatures.hrms.employeeManagement.employeeQualification.contextId,
        buttonContextId:
            state.auth.user.appFeatures.hrms.employeeManagement.employeeQualification.contextId,
        perm: state.auth.user.permissions,
        mediumAppParams: state.hrms.mediumAppParams,
        employeeKey: state.auth.user.employeeIdHash,
        admin: 1,
    }),
    {
        addEmployeeQualifications: EmployeeActions.addEmployeeQualifications,
        addEmployeeCertificate: EmployeeActions.addEmployeeCertificate,
    },
)
@ToastHoc()
export default class EmployeeQualification extends Component {
    constructor(props) {
        super(props);
        this.state = {
            QUAL: '',
            Graduate: '',
            Secondary: '',
            Doctorate: '',
            Illiterate: '',
            'Higher Secondary': '',
            PostGraduate: '340',
        };
    }
    componentDidMount = () => {
        const qualifications = [];
        this.props.appParams.forEach(param => {
            if (['QUAL'].includes(param.name)) {
                if (param.values) {
                    qualifications[param.name] = Object.values(param.values).map(v => {
                        Object.keys(this.state).map(() => {
                            if (v.value === 'Graduate') {
                                this.setState({ Graduate: v.id });
                            }
                            if (v.value === 'Secondary') {
                                this.setState({ Secondary: v.id });
                            }
                            if (v.value === 'Doctorate') {
                                this.setState({ Doctorate: v.id });
                            }
                            if (v.value === 'Illiterate') {
                                this.setState({ Illiterate: v.id });
                            }
                            if (v.value === 'Higher Secondary') {
                                this.setState({ 'Higher Secondary': v.id });
                            }
                            if (v.value === 'Post Graduate') {
                                this.setState({ PostGraduate: v.id });
                            }
                            return true;
                        });
                        return true;
                    });
                }
            }
        });
    };
    handleSubmit = async val => {
        const dataToSend = [];
        const { employeeKey } = this.props;
        if (!_.isEmpty(val.Graduate)) {
            val.Graduate.qualificationCategoryId = this.state.Graduate;
            val.Graduate.employeeKey = employeeKey;
            dataToSend.push(val.Graduate);
        }
        if (!_.isEmpty(val.Secondary)) {
            val.Secondary.qualificationCategoryId = this.state.Secondary;
            val.Secondary.employeeKey = employeeKey;
            dataToSend.push(val.Secondary);
        }
        if (!_.isEmpty(val.Doctorate)) {
            val.Doctorate.qualificationCategoryId = this.state.Doctorate;
            val.Doctorate.employeeKey = employeeKey;
            dataToSend.push(val.Doctorate);
        }
        if (!_.isEmpty(val.Illiterate)) {
            val.Illiterate.qualificationCategoryId = this.state.Illiterate;
            val.Illiterate.employeeKey = employeeKey;
            dataToSend.push(val.Illiterate);
        }
        if (!_.isEmpty(val['Higher Secondary'])) {
            val['Higher Secondary'].qualificationCategoryId = this.state['Higher Secondary'];
            val['Higher Secondary'].employeeKey = employeeKey;
            dataToSend.push(val['Higher Secondary']);
        }
        if (!_.isEmpty(val['Post Graduate'])) {
            val['Post Graduate'].qualificationCategoryId = this.state.PostGraduate;
            val['Post Graduate'].employeeKey = employeeKey;
            dataToSend.push(val['Post Graduate']);
        }

        const dataTobeSaved = dataToSend.map(async data => {
            data.employeeKey = employeeKey;
            await this.props.addEmployeeQualifications(data);
            this.props.setToast({
                message: 'Qualifications add sucessfully!',
                toastType: 'success',
            });
        });
        await Promise.all(dataTobeSaved);

        let trainingDataToSend;

        if (!_.isEmpty(val.detailOfTraining[0])) {
            trainingDataToSend = val.detailOfTraining.map(async training => {
                training.employeeKey = employeeKey;
                await this.props.addEmployeeCertificate(training);
                this.props.setToast({
                    message: 'Qualifications add sucessfully!',
                    toastType: 'success',
                });
            });
            await Promise.all(trainingDataToSend);
        }
    };

    render() {
        const { contextId, buttonContextId, perm, appParams, admin } = this.props;
        const options = {};
        appParams.forEach(param => {
            if (['MEDM', 'QUAL'].indexOf(param.name) === -1) return;

            options[param.name] = [];

            if (param.values) {
                options[param.name] = Object.values(param.values).map(v => ({
                    label: v.value,
                    value: v.id,
                }));
            }
        });
        return (
            <div>
                {admin === 1 ? (
                    <Page title="Employee Qualification" contextId={contextId}>
                        <EmployeeQualificationForm
                            contextId={contextId}
                            buttonContextId={buttonContextId}
                            perm={perm}
                            mediumAppParams={options.MEDM}
                            qualificationAppParams={options.QUAL}
                            onSubmit={this.handleSubmit}
                        />
                    </Page>
                ) : (
                    <div>
                        <EmployeeQualificationForm
                            contextId={contextId}
                            buttonContextId={buttonContextId}
                            perm={perm}
                            mediumAppParams={options.MEDM}
                            qualificationAppParams={options.QUAL}
                            onSubmit={this.handleSubmit}
                        />
                    </div>
                )}
                <ErrorToast />
            </div>
        );
    }
}

employeeQualification.js

import React, { Component } from 'react';
import { Field, reduxForm, FieldArray } from 'redux-form';
import { canWrite } from 'utils/roleAccessControl';
import { Button } from 'components';
import formStyles from 'components/Form/formStyles.scss';
import layoutStyles from 'modules/Configuration/components/ConfigLayout/ConfigPageLayout/style.scss';

import { Input, Select } from 'components/Form';
import styles from './style.scss';
// import employeeQualificationValidations from './validations.js';
import validate from './validations';

const renderSchools = ({ fields, data, qualificationData }) => (
    <tbody>
        {fields.map((qualificationDataschool, index) => (
            // eslint-disable-next-line react/no-array-index-key
            <tr key={index}>
                <td>
                    {index !== 0 && (
                        <span>
                            <b>
                                {qualificationData} {index + 1}
                            </b>
                        </span>
                    )}
                    {index === 0 && (
                        <span>
                            <b>{qualificationData}</b>
                        </span>
                    )}
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.degreeName`}
                        component={Input}
                        placeholder="Degree Name"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.instituteName`}
                        component={Input}
                        placeholder="Institue Name"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.universityName`}
                        component={Input}
                        placeholder="Board/University"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.entryYear`}
                        component={Input}
                        placeholder="Year of Passing"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.exitYear`}
                        component={Input}
                        placeholder="Year of Leaving"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.majorSubjects`}
                        component={Input}
                        placeholder="Major Subjects"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.marks`}
                        component={Input}
                        placeholder="Marks/Division"
                    />
                </td>
                <td>
                    <Field
                        name={`${qualificationData}.mediumId`}
                        type="select"
                        component={Select}
                        placeholder="Medium of Instructions"
                        options={data}
                        required
                    />
                </td>
                {/* Discussed with Rahul for future purpose */}
                {/* <td className={styles.addButton}>
                    {index === 0 && (
                        <Button type="button" onClick={() => fields.push({})}>
                            Add
                        </Button>
                    )}
                    {index !== 0 && (
                        <Button
                            type="button"
                            btnType="unstyled"
                            className={styles.removeAct}
                            onClick={() => fields.remove(index)}
                            icon="close"
                        >
                            Remove
                        </Button>
                    )}
                </td> */}
            </tr>
        ))}
    </tbody>
);

const renderDetailOfTraining = ({ fields }) => (
    <fieldset>
        <legend>Institute 1</legend>
        {fields.map((institute, index) => (
            // eslint-disable-next-line react/no-array-index-key
            <div key={index} className={styles.affiliationsRow}>
                {index !== 0 && (
                    <p className={styles.affiliationTitle}>
                        <span>Institute {index + 1}</span>
                        <Button
                            type="button"
                            btnType="unstyled"
                            className={styles.removeAct}
                            onClick={() => fields.remove(index)}
                            icon="close"
                        >
                            Remove
                        </Button>
                    </p>
                )}
                <div className={formStyles.threeCol}>
                    <Field
                        name={`${institute}.name`}
                        component={Input}
                        label="Institute Name"
                        placeholder="Enter the institute name"
                    />
                    <Field
                        name={`${institute}.description`}
                        type="textarea"
                        component={Input}
                        label="Description"
                        placeholder="Enter the Description"
                    />
                    <Field
                        name={`${institute}.duration`}
                        component={Input}
                        label="Duration"
                        placeholder="Enter the duration"
                    />
                </div>
            </div>
        ))}
        <div className={styles.addAffiliationAct}>
            <Button btnType="unstyled" type="button" onClick={() => fields.push({})}>
                <i className="fa fa-plus-circle" />
                <span>Add </span>
            </Button>
        </div>
    </fieldset>
);
@reduxForm({
    form: 'EmployeeQualificationForm',
    validate,
})
export default class EmployeeQualificationForm extends Component {
    static defaultProps = {
        mediumAppParams: {},
    };

    componentDidMount() {
        const defaultValues = { status: 'active' };

        defaultValues.schools = [{}];
        defaultValues.graduate = [{}];
        defaultValues.postGraduate = [{}];
        defaultValues.professional = [{}];
        defaultValues.diploma = [{}];
        defaultValues.other = [{}];
        defaultValues.detailOfTraining = [{}];
        defaultValues.schoolsList = [{}];

        this.props.initialize(defaultValues);
    }

    render() {
        const {
            mediumAppParams,
            qualificationAppParams,
            handleSubmit,
            form,
            buttonContextId,
            perm,
        } = this.props;

        const qualificationData = qualificationAppParams.map(item => (
            <FieldArray
                name="schools"
                // component={renderSchools}
                component={renderQualification}
                data={mediumAppParams}
                qualificationData={item.label}
            />
        ));
        return (
            <form
                className={`${styles.schoolInfoForm} ${layoutStyles.schoolSetup}`}
                onSubmit={handleSubmit}
                noValidate
                autoComplete="off"
            >
                <div className={styles.primaryColWrap}>
                    <table>
                        <thead>
                            <tr>
                                <th>School/ College</th>
                                <th>Degree Name</th>
                                <th>Institute Name</th>
                                <th>Board/ University</th>
                                <th>Year of Passing</th>
                                <th>Year of Leaving</th>
                                <th>Major Subjects</th>
                                <th>Marks/% Division</th>
                                <th>Medium of Instruction</th>
                            </tr>
                        </thead>
                        {qualificationData}
                    </table>
                </div>
                <br />
                <br />
                <div>
                    <legend>Detail Of Certification </legend>
                    <FieldArray name="detailOfTraining" 
                                //component={renderDetailOfTraining} 
                                component={renderQualification}
                                />
                    <div className={styles.actWrap}>
                        <div className={styles.rightActWrap}>
                            <Button
                                hidden={!canWrite(perm, buttonContextId)}
                                type="submit"
                                btnType="primary"
                            >
                                <span>Save</span>
                                <i className="fa fa-angle-right" />
                            </Button>
                            {/* <Button
                                hidden={!canWrite(perm, buttonContextId)}
                                type="submit"
                                btnType="primary"
                            >
                                <span>Cancel</span>
                            </Button> */}
                        </div>
                    </div>
                </div>
            </form>
        );
    }
}

现在,根据整个流程更改需求。实际上,流程只是屏幕上的“添加更多”按钮,用户单击“添加更多”按钮,然后只显示一个字段。

这是新的屏幕,如下所示:

2

基本上我是React Redux的新手,实际上我已经借助Google或堆栈溢出和其他一些站点完成了之前的流程,因此如何完成此新流程和UI。

0 个答案:

没有答案