这是我的代码
const renderEventStartEndDate = entry => {
const { classes } = props;
const isValidStartDate = isDateValid(entry.startDate);
const isValidEndDate = isDateValid(entry.endDate);
if (isValidStartDate && isValidEndDate && entry.startDate !== entry.endDate) {
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
{` TO ${getFormattedEventDate(entry.endDate).toUpperCase()}`}
</div>
);
} else if (entry.startDate === entry.endDate && isValidStartDate && isValidEndDate) {
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
</div>
);
} else if ((isValidStartDate && !isValidEndDate) || (!isValidStartDate && isValidEndDate)) {
if (isValidStartDate)
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
</div>
);
if (isValidEndDate)
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.endDate).toUpperCase()}
</div>
);
}
我有一个应用程序,我想重用上面的代码,所以我特别希望减少这里的返回代码。我想制作一个如下所示的函数,然后在不同的组件中使用它。
export const isDateValid = date => {
const dateObj = new Date(date);
return !isNaN(dateObj.getTime());
};
最佳答案
很多重构需要,您可以首先将业务逻辑与 View 分离。就像解析日期和创建字符串一样。
示例:
const getDate = entry => {
const isValidStartDate = isDateValid(entry.startDate);
const isValidEndDate = isDateValid(entry.endDate);
if (isValidStartDate && isValidEndDate && entry.startDate !== entry.endDate) {
return `${getFormattedEventDate(
entry.startDate
).toUpperCase()} TO ${getFormattedEventDate(entry.endDate).toUpperCase()}`;
} else if (
entry.startDate === entry.endDate &&
isValidStartDate &&
isValidEndDate
) {
return `${getFormattedEventDate(entry.startDate).toUpperCase()}`;
} else if (
(isValidStartDate && !isValidEndDate) ||
(!isValidStartDate && isValidEndDate)
) {
if (isValidStartDate)
return `${getFormattedEventDate(entry.startDate).toUpperCase()} `;
if (isValidEndDate)
return `${getFormattedEventDate(entry.endDate).toUpperCase()}`;
}
};
const renderEventStartEndDate = entry => {
const { classes } = props;
return <div className={classes.textContainer}>{getDate(entry)}</div>;
};
关于javascript - 如何制作一个可重用的函数,以便我保持 DRY 的良好实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60970202/