我觉得我在这个 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 emptyValues = insightName + insightDescription + createdBy + category + role + insightSource + assignTo === "";
当值为空时,将 scrollTo
放入 if
block 中
onSearchClick = () => {
const {
insightName,
insightDescription,
createdBy,
category,
role,
insightSource,
assignTo,
endDate,
startDate
} = this.state;
const emptyValues = insightName + insightDescription + createdBy + category + role + insightSource + assignTo === "";
const noEndDate = endDate === "" || endDate === null;
const noStartDate = startDate === "" || startDate === null;
if (emptyValues) {
window.scrollTo(500, 0);
if (noEndDate && noStartDate) {
this.setState({
isFormValid: false
});
} else if (noEndDate) {
this.setState({
showEndDateMsg: true
});
} else if (noStartDate) {
this.setState({
showStartDateMsg: true
});
}
} else {
this.setState({
showTable: true
});
}
};
关于javascript - 有没有更简单的方法来编写这个 React 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980561/