【发布时间】:2021-09-29 09:09:28
【问题描述】:
我正在写一个条件 if else。有多个 else 语句。最干净的写法是什么?以及最好的编码方式。
PS 我是 reactJS 新手。
if (type === activity.fetchPeople && loading) {
await store.dispatch(fetchPeople(store, 20, 0, params.sectionType));
store.dispatch(showGlobalLoader(false));
} else if (type === activity.pathfallRevert) {
await store.dispatch(fetchactivityfallRevert(store, params.userId, 20, 0));
activityPro = `${labels.pathfallRevert} (${params.count})`;
store.dispatch(showGlobalLoader(false));
} else if (type === activity.pathfall) {
await store.dispatch(fetchactivityfall(store, params.userId, 20, 0));
activityPro = `${labels.pathfall} (${params.count})`;
store.dispatch(showGlobalLoader(false));
} else if (type === activity.road) {
await store.dispatch(fetchRoads(store, params.userId, 20, 0));
activityPro = `${labels.road} (${params.count})`;
store.dispatch(showGlobalLoader(false));
} else if (type === activity.movers) {
await store.dispatch(fetchmovers(store, params.userId, 20, 0));
activityPro = `${labels.movers} (${params.count})`;
store.dispatch(showGlobalLoader(false));
} else {
store.dispatch(showGlobalLoader(false));
}
谢谢
【问题讨论】:
-
你可以使用相同的开关盒
-
在这种情况下,我通常使用字典/地图(在 JS 中它只是一个对象)。例如,您可以执行以下操作:
activityPro = {fetchPeople: null, pathfallRevert: ${labels.pathfallRevert} (${params.count}, /* remaining if-branches */}[type],然后对store.dispatch的 args 执行类似操作,并在最后使用从索引对象中选择的适当 args 调用该函数。
标签: javascript reactjs if-statement ecmascript-6