Как исправить несколько полей в одном массиве полей, а также «добавить еще», чтобы открыть массив из одного поля? - PullRequest
0 голосов
/ 26 марта 2019

Я получил домашнее задание, которое я сделал.В 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

По сути, я нахожусь в нововведении по реагированию на редукцию, на самом деле у меня есть предыдущий поток с помощью Google или переполнения стека и некоторых других сайтов, так что, как завершить этот новый поток и пользовательский интерфейс.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...