如何避免嵌套三元运算符



这是我的代码,它经常重复,我想避免这种情况:

{ isDataLoading ? (
<MyLoadingComponent />
) : !products ? (
<ThereIsNoDataComponent />
) : ( <div>Some text</div> )
}

我怎样才能写这个来避免嵌套的三元运算符?

谢谢大家

干杯

您可以将逻辑包装在一个函数中,然后从jsx块调用它

const render = () =>{
if(isDataLoading) return <MyLoadingComponent />
if(!products) return  <ThereIsNoDataComponent />
return <div>Some text</div>
}
return render()

这种情况似乎是一种在应用程序中可能多次发生的模式,因此可能值得实现另一个组件来处理此逻辑,例如

<Loader isLoading={isDataLoading} hasData={!!products} >
<Products product={products} />
</Loader>

加载器组件仅在有数据且未加载时才呈现子组件,否则将显示占位符消息。

有一个例子 https://codepen.io/wilski-micha/pen/bGGbewm

一种选择是制作 IIFE:

{
(() => {
if (isDataLoading) return (<MyLoadingComponent />);
if (!products) return (<ThereIsNoDataComponent />);
return (<div>Some text</div>);
})()
}

或者,如果要避免每次都重新创建函数:

const render = (isDataLoading, products) => {
if (isDataLoading) return (<MyLoadingComponent />);
if (!products) return (<ThereIsNoDataComponent />);
return (<div>Some text</div>);
};

{ render(isDataLoading, products) }

我正在使用这个自定义助手:

const switchTrue = (object) => {
const { default: defaultValue, ...rest } = object;
const obj = { default: defaultValue, ...rest };
const result = Object.keys(obj).reduce((acc, cur) => {
return {
...acc,
[cur === 'default' ? 'true' : cur]: obj[cur],
};
}, {});
return result['true'];
};
const isDataLoading = false;
const products = false;
const component = switchTrue({
[`${Boolean(isDataLoading)}`]: '<MyLoadingComponent />',
[`${!products}`]: '<ThereIsNoDataComponent />',
default: '<div>Some text</div>',
});
console.log(component) // <ThereIsNoDataComponent />

最新更新