如何避免嵌套三元运算符

问题描述 投票:3回答:3

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

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

如何编写此代码以避免嵌套三元运算符?

谢谢你们

欢呼声

javascript html reactjs ternary-operator
3个回答
1
投票

一种选择是进行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) }

4
投票

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

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

return render()

1
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.