一个功能中的多个条件

问题描述 投票:1回答:2

我正在我的应用上重新创建这种模块Ant Design Calendar,但是我可以在dateCellRender内部调用多个功能。如何根据所调用的内容执行?即使我没有调用它,它也总是执行holidayListDay

这是我称为dateCellRender的组件,用于分配日历中的每个日期

<Calendar
  dateCellRender={dateCellRender}
  monthCellRender={monthCellRender}
  onPanelChange={changeCalendarMode}
/>
const dateCellRender = value => {
  let holidayListDay = getHolidayListDay(value);
  let employeeStartLeave = getEmployeeStartLeave(value);

  if(holidayListDay) {
    //execute code here

  } else if(employeeStartLeave) {
    //execute code here

  }

};

这是我在上面叫的代码

const getHolidayListDay = value => {
  let holidayListDay = [...isHolidayDay];

  const calendarDates = value.toString();
  const formatCalendarDates = moment(calendarDates).format('YYYY-MM-DD');

  return (
    holidayListDay.find(
      item =>
        moment(item.holidayDate).format('YYYY-MM-DD') == formatCalendarDates
    ) || []
  );
};
const getEmployeeStartLeave = value => {
 let employeeLeaves = [...isEmployeeLeave];

 const calendarDates = value.toString();
 const formatCalendarDates = moment(calendarDates).format('YYYY-MM-DD');

 const filteredData = [].concat
  .apply([], employeeLeaves)
  .filter(item => item.startDate === formatCalendarDates);

 return filteredData;
};
reactjs ecmascript-6 antd
2个回答
0
投票

您的getHolidayListDay()函数总是返回true ish值(空数组的值为true)。

尝试将if更改为:

  if(holidayListDay && holidayListDay.length ) {
    //execute code here

  } else if(employeeStartLeave) {
    //execute code here

  }

0
投票

您的问题出在函数返回中。如果函数返回数组,则必须检查数组长度。因为在if条件下,空数组始终为true。例如,>

var test = [];
if(test)
    console.log('condition is true'); //it will output 'condition is true'

if(test && test.length>0)
    console.log('condition is false') //It will output nothing

对于您的代码。如果两个holidayListDay , employeeStartLeave函数都返回数组,则必须检查如下:

if(holidayListDay && holidayListDay.length ) {
    //your code
} else if(employeeStartLeave && employeeStartLeave) {
   //your code
}
© www.soinside.com 2019 - 2024. All rights reserved.