我觉得我在这个React函数中经常重复自己。我需要检查状态中的大多数字段是否为空,但是有些字段我不想检查。所以我不确定该怎么做。
这里是:
onSearchClick = () => {
const {insightName, insightDescription, createdBy, category, role, insightSource, assignTo, endDate, startDate} = this.state;
if(
insightName === "" &&
insightDescription === "" &&
createdBy === "" &&
category === "" &&
role === "" &&
insightSource === "" &&
assignTo === "" &&
(endDate === "" || endDate === null) &&
(startDate === "" || startDate === null)
)
{
window.scrollTo(500, 0);
this.setState({
isFormValid: false,
})
} else if (
insightName === "" &&
insightDescription === "" &&
createdBy === "" &&
category === "" &&
role === "" &&
insightSource === "" &&
assignTo === "" &&
(endDate === "" || endDate === null)
) {
window.scrollTo(500, 0);
this.setState({
showEndDateMsg: true
})
} else if (
insightName === "" &&
insightDescription === "" &&
createdBy === "" &&
category === "" &&
role === "" &&
insightSource === "" &&
assignTo === "" &&
(startDate === "" || startDate === null)
) {
window.scrollTo(500, 0);
this.setState({
showStartDateMsg: true
})
} else {
this.setState({
showTable: true
})
}
}
我想遵循DRY原则,但不确定该怎么做!任何建议将不胜感激。谢谢。
最佳答案
设置一个变量以包含您要不断检查的所有内容:
const isMostlyEmpty = insightName === "" &&
insightDescription === "" &&
createdBy === "" &&
category === "" &&
role === "" &&
insightSource === "" &&
assignTo === "";
然后,您可以在每个语句中重复使用该语句:
if(isMostlyEmpty &&
(endDate === "" || endDate === null) &&
(startDate === "" || startDate === null)) {
window.scrollTo(500, 0);
this.setState({
isFormValid: false,
});
} else if (isMostlyEmpty &&
(endDate === '' || endDate === null)) {
window.scrollTo(500, 0);
this.setState({
showEndDateMsg: true
});
} else if (isMostlyEmpty &&
(startDate === '' || endDate === null)) {
window.scrollTo(500, 0);
this.setState({
showStartDateMsg: true
});
} else {
this.setState({
showTable: true
});
}
关于javascript - 有没有更简单的方法来编写此React函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57980561/