【问题标题】:How to avoid nested ternary operators如何避免嵌套三元运算符
【发布时间】:2020-02-01 17:44:19
【问题描述】:

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

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

我怎样才能避免嵌套三元运算符?

谢谢大家

干杯

【问题讨论】:

  • 你能提供更多的上下文吗?你想让它更具可读性还是你想要实现什么?
  • 将每个“巢”提取到自己的返回函数中?
  • @Chris 只是我不喜欢这里的嵌套三元运算符,我想避免它们,任何方式都会很棒..
  • @Malcor 我该怎么做?

标签: javascript html reactjs ternary-operator


【解决方案1】:

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

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 />

【讨论】:

    【解决方案2】:

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

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

    加载器组件只有在有数据且未加载时才会渲染子组件,否则会显示占位符消息。

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

    【讨论】:

    • 不是我,但我认为您应该澄清 Loader 的外观。不清楚三元杂波是如何清除的。
    【解决方案3】:

    一种选择是创建一个 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) }
    

    【讨论】:

    • 为什么不在外部定义函数而不是在每次渲染时重新创建它?
    • 有点杂乱但我也喜欢这种方式,看起来比嵌套三元运算符好!
    • @Chris 这取决于isDataLoading 或products 的范围,这在问题中不存在,我猜可以使用它们调用命名函数
    • @CertainPerformance 它们几乎肯定是状态或道具,因为否则无法在突变后更新 React 组件。
    • @CertainPerformance 避免重新创建函数的代码仅适用于类组件。在函数式组件的世界里,你每次都会得到新的函数,因为渲染的组件默认不会被记忆。 “useMemo”钩子或“React.memo(...)”可以用来解决这个问题。
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2020-03-04
      • 2017-09-20
      相关资源
      最近更新 更多