【问题标题】:React: Advantages for conditionals to check the negative before the affirmative?反应:在肯定之前检查否定的条件的优势?
【发布时间】:2022-01-26 20:52:46
【问题描述】:

在 Javascript 中,if 语句检查是否满足有利条件似乎是一种普遍做法首先

例如参数或变量当前已定义并可用于使用:

const funcName = (necessaryParam) => {
  if (necessarryParam.length > 0) {
    console.log('condition met!');
    return; 
  }
console.log('condition not met!');
return;
}

在 React 中,我发现肯定肯定条件有机会跳过整个 return 语句:

const Component = (props) => {
  if (props)
  return (
    <YourComponent withProps={props} />
  )
}

对于需要通过几行代码进行解析才能说它们没有足够的信息来优化功能的组件:

function YourComponent(props) {
  return (
    { props && (
        <ComponentEveryoneWantsThatNeedsProps withProps={props} />
      )
    }
    { !props && (
        <ComponentThatTellsYouYoureScrewed />
      )
   )
}

在一般情况下,如果我有一个组件的较大部分将在肯定条件下呈现,与在否定条件下呈现的较小部分相比,我是否应该检查是否是肯定条件在 React 解析更大的肯定条件代码块之前不满足? (这被认为是“良好做法”吗?)

例如检查你是否没有我需要的东西更容易,因为我可以告诉你早点离开......:

function ConditionallyRenderedComponent(props) {
  return (
    { !props && (
      <div>
        <OneComponent />
      </div>
      )
    } // vs
    { props && (
      <div>
        <FirstComponent>
         <H1>
          <SecondComponent />
         </H1>
        </FirstComponent>
      </div>
      )
    }
  )
}

显然这些都是非常人为的例子,但希望我的问题是有道理的。

是否有理由只公开最简单的事情?有没有一种您认为效果最好的特定方法?

这真的很重要吗?

关于在 React 中构造条件,你有什么有趣或有用的材料想分享吗?

【问题讨论】:

    标签: javascript reactjs if-statement conditional-statements ternary


    【解决方案1】:

    条件检查的排序有多种注意事项。一些例子:

    性能优化:例如过滤无效输入:

    function calculateValue (...inputs) {
      if (!inputs.every(n => typeof n === 'number')) return NaN;
      // ...computationally expensive logic
      return expensiveResult;
    }
    

    在僵局中抛出异常以确保仅在有效状态下继续发生:

    function findNestedSiblings () {
      // ...
      const element = document.querySelector(/* selector */);
      if (!element) throw new Error('msg');
    
      // element exists
      // continue...
    }
    

    除了性能优化之外,有时条件的结构化还有助于提高代码的可读性(这开始进入人们的视野)。如果您可以先处理一个终止条件(例如,导致returnthrowbreakcontinueyield 等),您通常不需要else 块和可以将您的代码保持在范围内的顶级缩进:我发现这非常有用并且通常与性能排序保持一致。

    【讨论】:

    • 我在 nodejs/REST 操作中看到了您的第二个示例的顺序,但对于 React 组件,最常见的顺序相反。这有什么原因吗?此外,您使用Array.every() 检查typeof [inputs] 的示例很有用,您有类似的{ Object.values } 吗?谢谢
    • 我不确定您所说的“相反”是什么意思。 Object.values() 评估为一个数组,因此它的工作方式相同。
    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 2022-11-15
    • 2020-03-12
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多