【发布时间】:2022-01-26 20:52:46
【问题描述】:
在 Javascript 中,if 语句检查是否满足有利条件似乎是一种普遍做法首先,
例如参数或变量当前已定义并可用于使用:
const funcName = (necessaryParam) => {
if (necessarryParam.length > 0) {
console.log('condition met!');
return;
}
console.log('condition not met!');
return;
}
在 React 中,我发现肯定肯定条件有机会跳过整个 return 语句:
const Component = (props) => {
if (props)
return (
<YourComponent withProps={props} />
)
}
对于需要通过几行代码进行解析才能说它们没有足够的信息来优化功能的组件:
function YourComponent(props) {
return (
{ props && (
<ComponentEveryoneWantsThatNeedsProps withProps={props} />
)
}
{ !props && (
<ComponentThatTellsYouYoureScrewed />
)
)
}
在一般情况下,如果我有一个组件的较大部分将在肯定条件下呈现,与在否定条件下呈现的较小部分相比,我是否应该检查是否是肯定条件在 React 解析更大的肯定条件代码块之前不满足? (这被认为是“良好做法”吗?)
例如检查你是否没有我需要的东西更容易,因为我可以告诉你早点离开......:
function ConditionallyRenderedComponent(props) {
return (
{ !props && (
<div>
<OneComponent />
</div>
)
} // vs
{ props && (
<div>
<FirstComponent>
<H1>
<SecondComponent />
</H1>
</FirstComponent>
</div>
)
}
)
}
显然这些都是非常人为的例子,但希望我的问题是有道理的。
是否有理由只公开最简单的事情?有没有一种您认为效果最好的特定方法?
这真的很重要吗?
关于在 React 中构造条件,你有什么有趣或有用的材料想分享吗?
【问题讨论】:
标签: javascript reactjs if-statement conditional-statements ternary