我有一个使用助手功能的组件来获取日期列表,然后在它们上进行映射。在检索到的数据中,给定阶段不会总是有日期,因此我添加了逻辑,如果未定义该特定日期,则返回空字符串。
helper函数获取一个日期,其中属性Phase ='phase name'。
我能够将其中的一部分提取到一个辅助函数中,但是感觉仍然有一种更简洁的编写方法。有人可以帮忙吗?
助手功能
const getCoursePhaseDate = function(coursePhases, coursePhase) {
return coursePhases.toJSON().filter((obj) => {
return obj.phase === coursePhase;
});
};
export default getCoursePhaseDate;
组件
import React from 'react';
import moment from 'moment';
// helpers
import getCoursePhaseDate from './helpers/getRehabStateDate';
const CourseInfo = ({ coursePhases }) => {
const prep = getCoursePhaseDate(coursePhases, 'Prep')[0] && getCoursePhaseDate(coursePhases, 'Prep')[0].enteredOn || '';
const intro = getCoursePhaseDate(coursePhases, 'Intro')[0] && getCoursePhaseDate(coursePhases, 'Intro')[0].enteredOn || '';
const main = getCoursePhaseDate(coursePhases, 'Main')[0] && getCoursePhaseDate(coursePhases, 'Main')[0].enteredOn || '';
const bonus = getCoursePhaseDate(coursePhases, 'Bonus')[0] && getCoursePhaseDate(coursePhases, 'Bonus')[0].enteredOn || '';
const coursePhaseDates = [prep, intro, main, bonus];
return (
<div>
<div>
{
coursePhaseDates.map((date, i) => {
return (
<span style={ styles.enteredOnDate } key={ i }>{ date }</span>
);
})
}
</div>
</div>
);
};
export default CourseInfo;
答案 0 :(得分:1)
如果您想使其更简洁明了,请使用箭头功能:
const getCoursePhaseDate = (coursePhases, coursePhase) => coursePhases.toJSON().filter((obj) => obj.phase === coursePhase));
甚至具有破坏性的清理器:
const getCoursePhaseDate = (coursePhases, coursePhase) => coursePhases.toJSON().filter(({ phase }) => phase === coursePhase));
答案 1 :(得分:1)
此行及类似行可以使用解构和默认参数进行如下修改
const {enteredOn: prep = ''} = getCoursePhaseDate(coursePhases, 'Prep')[0] || {};
这也减少了两次函数调用。
希望它会有所帮助:)
答案 2 :(得分:1)
const hasOwn = {}.hasOwnProperty;
const getCoursePhaseDate = function(coursePhases, coursePhase) {
const foundPhase = coursePhases.toJSON().find(obj => {
return obj.phase === coursePhase && hasOwn.call(obj, 'enteredOn');
});
return foundPhase != null ? foundPhase.enteredOn : '';
};
export default getCoursePhaseDate;
import React from 'react';
import moment from 'moment';
// helpers
import getCoursePhaseDate from './helpers/getRehabStateDate';
const CourseInfo = ({ coursePhases }) => {
const coursePhaseDates = ['Prep', 'Intro', 'Main', 'Bonus'].map(phase => {
return getCoursePhaseDate(coursePhaseDates, phase);
});
return (
<div>
<div>
{
coursePhaseDates.map((date, i) => {
return (
<span style={ styles.enteredOnDate } key={ i }>{ date }</span>
);
})
}
</div>
</div>
);
};
export default CourseInfo;