這是我的代碼,我想打破它的多功能(干凈的代碼!),這兩個部分
(status===edited)和(status === added)兩個不同的功能(dataindex===ReportEffectiveDate)和(dataindex=== EffectiveDate)我。怎么可以把這些if else在另一份宣告中function,然后我用這個功能對各狀態。我完全想知道哪種方式更好:我使用多個 if 和else if或使用多個function代碼?感謝您的幫助!
function handleTableRowChange(record: LoadModel, oldValue: any, newValue: any, dataIndex: string) {
console.log(record, oldValue, newValue, dataIndex);
const status: RowStatus = tableStore.getRowStatus(record);
if (!!newValue) {
if (dataIndex === 'ReportEffectiveDate') {
if (record.EffectiveDate > record.ReportEffectiveDate) {
record.EffectiveDate = null;
tableStore.update(record);
Modal.error({
content: translate('ReportEffectiveDatecantbelessthanoldeffectivedate'),
});
console.log('error');
} else if (record.EffectiveDate == record.ReportEffectiveDate) {
record.ReportEffectiveDate = null;
tableStore.update(record);
}
}
if (dataIndex === 'EffectiveDate') {
if (status === 'added') {
const isValid: boolean = checkIsEffectiveDateValid(record);
if (!isValid) {
record.EffectiveDate = null;
tableStore.update(record);
}
} else if (status === 'edited') {
const maxEffectiveDateRecord: LoadModel = getMaxEffectiveDateRecord(record);
if (record.EffectiveDate > maxEffectiveDateRecord.EffectiveDate) {
if (newValue < maxEffectiveDateRecord.EffectiveDate) {
record.EffectiveDate = oldValue;
tableStore.update(record);
}
}
}
}
}
}
uj5u.com熱心網友回復:
您仍然需要添加檢查以查看要呼叫的內容。你可以把事情分解成一個函式并呼叫它。使用開關可能很簡單
function handleTableRowChange(........) {
..........
switch (dataIndex) {
case 'ReportEffectiveDate':
reportEffectiveDateFunction(record);
break;
case 'EffectiveDate':
effectiveDateFunction(record);
break;
case 'edited':
editedFunction(record);
break;
}
}
其他選項是將物件或類與方法一起使用
const processingFunctions = {
ReportEffectiveDate: (report) => {
console.log('ReportEffectiveDate', report);
},
EffectiveDate: (report) => {
console.log('EffectiveDate', report);
},
edited: (report) => {
console.log('edited', report);
},
}
function handleTableRowChange(........) {
..........
const action = processingFunctions[dataIndex];
if (action) {
action(report);
} else {
// no command found....
}
}
uj5u.com熱心網友回復:
看起來您使用的是 TypeScript... 就像任何類似 OOP 的語言一樣,您實際上可以將它提升一個級別并定義一個interface.
為了便于閱讀,我建議在 if-else-if-if... 中使用函式或切換到case陳述句。當您更改函式本身時,將代碼移動到函式中有助于可維護性,而且您不會更改代碼的 if-else 部分,代碼更改更少,錯誤更少。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341322.html
標籤:javascript 反应 功能 if 语句
下一篇:不使用等待時洗掉異步是否安全?
