!loading
我有3个以上的条件并且有3个不同的html块,上面的代码只是工作但我觉得!loading
声明太可重复,如何改进上面的代码?
{{1}}是必须的,因为在API提取待处理之前我不想显示任何内容。
答案 0 :(得分:2)
我会创建一个这样的函数:
function getContent(status) {
switch (status) {
case 'paid':
return (<div>display content base on paid</div>);
case 'active':
return (<div>display content base on active</div>);
default:
return (<div>display something base on not active and not paid</div>);
}
}
...然后将您的代码块更改为:
{!loading && getContent(ad.status)}
答案 1 :(得分:0)
考虑拆分成自己的组件/功能然后执行此操作:
if (loading) {
return null;
}
{(ad.status !== 'active' && ad.status !== 'paid') && <div>
display something base on not active and not paid
</div>}
{ad.status === 'paid' && <div>display content base on paid</div>}
{ad.status === 'active' && <div>display content base on active</div>}
答案 2 :(得分:0)
我真的很喜欢recompose
:
const BaseComponent = ()=>(
<div>this is your most common case (blue sky scenario)</div>
);
// add special cases as branches
const FinalComponent = compose(
branch(({loading}) => loading, renderNothing)),
branch(({ad}) => ad.paid, renderComponent(PaidContent))),
branch(({ad}) => !ad.active, renderComponent(InactiveContent))),
)(BaseComponent)
我可能混淆了哪种情况是您的正常情况,哪些情况是例外情况。但是这可以让你了解它是如何工作的。
在我们的项目中,我们的Base组件永远不会包含加载和边缘情况。这使得正常的案例代码更容易阅读。
注意:branch
来电的顺序非常重要。