重构日期的 if 语句

问题描述

我被要求重构以下内容

 if (
                      cell.column.id === 'maintenance_from' ||
                      cell.column.id === 'reg_number_CPDP_date' ||
                      cell.column.id === 'license_date_of_issue'
                    ) {
                      let timestamp = '';
                      Object.keys(cell?.row?.original).forEach(
                        (item: any) => {
                          if (
                            item === 'maintenance_from' ||
                            item === 'reg_number_CPDP_date' ||
                            item === 'license_date_of_issue'
                          ) {
                            timestamp = cell?.row?.original[item];
                          }
                        }
                      );
                      return (
                        <td {...cell.getCellProps()}>
                          {DateParse(timestamp)}
                        </td>
                      );

来自以下代码

    import React,{ useCallback,useEffect,useState } from 'react';
import { ExtendedTableColumnProps } from 'shared/types/table';
import { useTranslation } from 'react-i18next';
import { Box,Button,CheckBox,Grid,Tooltip } from '@material-ui/core';
import Loader from 'shared/components/Loader/Loader';
import useTranslationRedux from 'shared/hooks/useTranslation';
import { useAsyncFn,useMount } from 'react-use';
import I18nService from 'shared/services/I18nService';
import { PORTAL_BASE_ROUTE } from '../../../shared/navigation/portalRoutes';
import DateParse from '../../../shared/utils/parseDate';

interface TableProps {
  loading?: boolean;
  classes: any;
  instance: any;
  formProps: any;
  setLinkedobjectId?: any;
  type: any;
  selectedLayer: any;
  setFeatureId?: any;
}

const LinkedobjectsFormRowTable: React.FC<TableProps> = ({
  classes,instance,formProps,setLinkedobjectId,type,loading,selectedLayer,setFeatureId,}) => {
  const { t } = useTranslation();
  const [checkBoxesstate,setCheckBoxesstate] = useState<any>({});

  const { language } = useTranslationRedux();

  const arrOfNonSpatialData = [
    'logical_networks','buildings','dam_usages','legal_entities','licenses','maintenances','municipalities','water_volumes','water_pump_station_pumps','sewer_pump_station_pumps','irrigate_system_drainage_data','wwtp_data_per_year','water_supply_systems','wastewater_disposal_and_treatment_systems','sewer_networks',// 'measurement_devices',];

  const [featuresTranslationsResponse,loadTranslations] = useAsyncFn(
    (layerName: string) => I18nService.layersTransations.getSingle(layerName),[]
  );

  useMount(() => {
    if (formProps.initialValues.linkedobjectId) {
      setCheckBoxesstate({
        [formProps.initialValues.linkedobjectId]: true,});
    }
  });

  const reloadTranslatons = () => {
    const nonSpatialView = 'view_';

    if (arrOfNonSpatialData.includes(selectedLayer)) {
      loadTranslations(nonSpatialView.concat(selectedLayer));
    } else {
      loadTranslations(selectedLayer);
    }
  };

  useEffect(reloadTranslatons,[language]);

  const featuresTranslations: any =
    featuresTranslationsResponse.value?.data ?? [];

  const translateHeader = useCallback(
    (element: string) => {
      const translation = featuresTranslations?.columns?.find(
        (c: any) => c?.columnKey === element
      );
      return translation?.value.length > 0 ? translation?.value : t(element);
    },[featuresTranslations,t]
  );

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement>,isNonSpacial: boolean,row: any
  ) => {
    const checkBoxVal = Number(e.target.name);

    if (isNonSpacial) {
      Object.keys(row.original).forEach((item: any) => {
        if (item.startsWith('pk') && item.endsWith('id')) {
          if (setLinkedobjectId) {
            setLinkedobjectId(row.original[item]);
          }
          formProps.setFieldValue('linkedobjectId',row.original[item]);
          setCheckBoxesstate({
            [row.original[item]]: e.target.checked,});
        } else if (item.includes('featureId') && setFeatureId) {
          setFeatureId(row.original[item].split('.')[0]);
        }
      });
    } else {
      setCheckBoxesstate({
        [e.target.name]: e.target.checked,});
      if (e.target.checked) {
        formProps.setFieldValue('linkedobjectId',checkBoxVal);
        if (setLinkedobjectId) {
          setLinkedobjectId(checkBoxVal);
        }
      } else {
        formProps.setFieldValue('linkedobjectId','');
        if (setLinkedobjectId) {
          setLinkedobjectId('');
        }
      }
    }
  };

  const {
    getTableProps,getTableBodyProps,headerGroups,prepareRow,rows,} = instance;

  return (
    <Grid item xs={12}>
      {loading ? (
        <Loader text={t('pleaseWait')} isLoading size={100} />
      ) : (
        <Box
          className={classes.featuresTableContainer2}
          style={{ padding: 0 }}
          mt={2}
        >
          <Box className="tableScrollContainer" style={{ maxHeight: '200px' }}>
            <table
              {...getTableProps()}
              cellSpacing={0}
              className={classes.table}
            >
              <thead>
                {headerGroups.map((group: any) => (
                  <tr {...group.getHeaderGroupProps()}>
                    {(group.headers as ExtendedTableColumnProps[]).map(
                      column => {
                        return (
                          <th {...column.getHeaderProps()}>
                            <Box display="flex" alignItems="center">
                              {translateHeader(column.id)}
                            </Box>
                          </th>
                        );
                      }
                    )}
                  </tr>
                ))}
              </thead>
              <tbody {...getTableBodyProps()}>
                {rows.map((row: any) => {
                  prepareRow(row);
                  return (
                    <tr {...row.getRowProps()}>
                      {row.cells.map((cell: any) => {
                        if (/*fkNetworkElId &&*/ cell.column.id === 'choose') {
                          const nameKey: string =
                            Object.keys(cell.row.original).find(
                              key => key.startsWith('pk') && key.endsWith('id')
                            ) || '';
                          const nameValue =
                            type !== 'nonSpatialObjects'
                              ? cell.row.original.fk_network_element_id
                              : cell.row.original[nameKey];
                          return (
                            <td {...cell.getCellProps()}>
                              <CheckBox
                                value={nameValue}
                                checked={checkBoxesstate[nameValue] || false}
                                onChange={e =>
                                  handleChange(
                                    e,type === 'nonSpatialObjects',cell.row
                                  )
                                }
                                name={nameValue}
                              />
                            </td>
                          );
                        }

                        if (
                          cell.column.id === 'options' &&
                          type !== 'nonSpatialObjects'
                        ) {
                          return (
                            <td {...cell.getCellProps()}>
                              <Tooltip title={`${t('linkedobjectsInfo')}`}>
                                <span>
                                  <Button
                                    className={classes.button}
                                    onClick={() => {
                                      const layerName = cell.row.original.featureId.split(
                                        '.'
                                      );
                                      const url = `${PORTAL_BASE_ROUTE}/linked-objects/${cell.row.original.fk_network_element_id}/${layerName[0]}`;
                                      window.open(url,'_blank');
                                    }}
                                  >
                                    <i
                                      className={
                                        'fas fa-external-link-alt fa-lg'
                                      }
                                      style={{ margin: '3px 0 0 2px' }}
                                    />
                                  </Button>
                                </span>
                              </Tooltip>
                              <Tooltip title={`${t('showOnMap')}`}>
                                <span>
                                  <Button
                                    className={classes.button}
                                    onClick={() => {
                                      const layerName = cell.row.original.featureId.split(
                                        '.'
                                      );
                                      const url = `${PORTAL_BASE_ROUTE}?layer=${layerName[0]}&id=${cell.row.original.fk_network_element_id}`;
                                      window.open(url,'_blank');
                                    }}
                                  >
                                    <i
                                      className={'fas fa-map-marked-alt fa-lg'}
                                      style={{ margin: '3px 0 0 2px' }}
                                    />
                                  </Button>
                                </span>
                              </Tooltip>
                            </td>
                          );
                        }

                        if (
                          cell.column.id === 'maintenance_from' ||
                          cell.column.id === 'reg_number_CPDP_date' ||
                          cell.column.id === 'license_date_of_issue'
                        ) {
                          let timestamp = '';
                          Object.keys(cell?.row?.original).forEach(
                            (item: any) => {
                              if (
                                item === 'maintenance_from' ||
                                item === 'reg_number_CPDP_date' ||
                                item === 'license_date_of_issue'
                              ) {
                                timestamp = cell?.row?.original[item];
                              }
                            }
                          );
                          return (
                            <td {...cell.getCellProps()}>
                              {DateParse(timestamp)}
                            </td>
                          );
                        } else {
                          return (
                            <td {...cell.getCellProps()}>
                              {cell.render('Cell')}
                            </td>
                          );
                        }
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Box>
        </Box>
      )}
    </Grid>
  );
};

export default LinkedobjectsFormRowTable;

这么多的问题是,我怎样才能把这个片段做得更小更好? 这么多问题是,我怎样才能让这个片段更小、更好? 这么多问题是,我怎样才能让这个片段更小、更好? 这么多问题是,我怎样才能让这个片段更小、更好? 这么多问题是,我怎样才能让这个片段更小、更好? 这么多问题是,我怎样才能把这个片段做得更小更好?

解决方法

你可以用 array.includes 方法替换多个 if..else。

const STACK1 = ['maintenance_from','reg_number_CPDP_date','license_date_of_issue'];
if (STACK1.includes(cell.column.id)) {
    let timestamp = '';
    Object.keys(cell?.row?.original).forEach(
        (item: any) => {
            const STACK2 = ['maintenance_from','license_date_of_issue']
            if (STACK2.includes(item)) {
                timestamp = cell?.row?.original[item];
            }
        });