这里是我的代码,它经常重复,我想避免这种情况:
{ isDataLoading ? (
<MyLoadingComponent />
) : !products ? (
<ThereIsNoDataComponent />
) : ( <div>Some text</div> )
}
如何编写此代码以避免嵌套三元运算符?
谢谢你们
欢呼声
一种选择是进行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) }
您可以将逻辑包装在函数中,然后从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>
仅当有数据且未加载时,加载程序组件才会呈现子组件,否则将显示占位符消息。