I know this question has been asked before, but the usual answers bring another (potential) problem and doubts to my mind.
上下文
我有一个函数,它根据两个参数paramA
和paramB
返回要渲染的组件.现在,代码看起来像这样:
if (paramA === paramATypes.PRE) {
if (paramB === paramBTypes.REQUEST) {
detailedView = (
<ComponentA
requestDetails={requestDetails as RequestDetailsDto<ComponentADto>}
/>
);
} else if (paramB === paramBTypes.MODIFICATION) {
detailedView = (
<ComponentB
requestDetails={
requestDetails as RequestDetailsDto<ComponentBDto>
}
/>
);
}
} else if (paramA === paramATypes.PRI) {
if (paramB === paramBTypes.REQUEST) {
detailedView = (
<ComponentC
requestDetails={requestDetails as RequestDetailsDto<ComponentCDto>}
/>
);
} else if (paramB === paramBTypes.MODIFICATION) {
detailedView = (
<ComponentD
requestDetails={
requestDetails as RequestDetailsDto<ComponentDDto>
}
/>
);
}
} else if...
这种情况还在继续,因为我们每种都有一些不同的类型,而且是each of them has a specific component that renders its properties in a certain way种.当然,仅仅能够描述情况就有点过于简单化了.
问题是,我可以try 这样做,就像我通常对更简单的值所做的那样:
const dict = {
[paramATypes.PRE]: {
[paramBTypes.REQUEST]: <ComponentA
requestDetails={requestDetails as RequestDetailsDto<ComponentADto>}
/>,
[paramBTypes.MODIFICATION]: <ComponentB
requestDetails={
requestDetails as RequestDetailsDto<ComponentBDto>
}
/>,
},
...
}
然后这样称呼它:
const view = dict[paramA][paramB];
问题
我看到的问题是,使用"如果-地狱"时,只有在满足IF条件时才会处理组件的值.因此,在本例中,它将在每个调用中只计算/处理一个组件.
然而,如果我使用对象/字典范式,它将处理所有的值,因为它需要它来创建稍后要访问的实际对象,所以每次调用这个方法都会计算所有的可能性,只返回其中一个.
如果值只是声明或更简单的值,我不会有任何问题,但作为react 组件我不太确定.
问题是
我对这两种范式的处理方式正确吗?我能做些什么才能有一套更干净的条件?
也许将值定义包装在一个方法中,这样它只在我执行方法的结果时才被处理,就像在const view = dict[paramA][paramB]();
中一样?
我只是想知道which would be the best way to put this,所以它不仅是easier to read,而且还有good performance(和代码分析器中的good cognitive complexity).
谢谢!