【发布时间】:2019-06-10 09:11:18
【问题描述】:
我有一个像这样的渲染函数:
render() {
const statement = true
return (
<div>
{
statement &&
<div>
<p>
{this.buildStuff()}
</p>
<p>
{this.buildStuff()}
</p>
<p>
{this.buildStuff()}
</p>
</div>
}
</div>
);
}
为了避免调用buildStuff() 三次,我想将它分配给一个变量。如何在statement && 行后声明变量?
一个快速的解决方案是做
const statement = true
const stuff = statement ? buildStuff() : null;
但是这个解决方案使用两个分支而不是一个。
您可以在StackBlitz 上试用此代码。
这就是它在Razor 中的样子。
【问题讨论】:
-
const stuff = statement ? buildStuff() : null;有什么问题? -
为什么不能在return语句前做
const ui = statement && this.buildStuff(); return ... // just use ui here -
@hindmost 为什么要在一个应该足够的情况下做出两个陈述?
-
@aloisdg 然后按照@Yury Tarabanko 的建议使用
&& -
@aloisdg 你会牺牲可读性而一无所获。真的没什么。顺便说一句,我敢打赌,Rajesh 的解决方案的性能不如检查布尔值:)。它创建一个数组、临时对象、将被 gced 的匿名函数,并添加另一个函数调用。
标签: javascript reactjs jsx