【问题标题】:Declaration of constant in componentWillMount in React?React中componentWillMount中的常量声明?
【发布时间】:2018-09-13 18:21:12
【问题描述】:

就性能而言,第 1 名或第 2 名哪个更好?

const getCookieValue = readCookie('my_var') 应该声明在顶部,或者因为它的使用只是在一个条件下,所以最好将它保留在 if 语句中

方法 1

componentWillMount() {
  const {data1, data2} = this.props
  if(data1) {
    const getCookieValue = readCookie('my_var')
    if(getCookieValue === 'test_string') {
      // Statements ....
    }
  }
}

方法 2

componentWillMount() {
  const {data1, data2} = this.props
  const getCookieValue = readCookie('my_var')
  if(data1) {
    if(getCookieValue === 'test_string') {
      // Statements ....
    }
  }

}

【问题讨论】:

  • 性能方面,仅在需要该变量的逻辑路径上执行操作会更快。但在这种情况下几乎可以忽略不计

标签: javascript reactjs performance ecmascript-6 react-lifecycle


【解决方案1】:

性能方面 - 方法 1,你回答了你的问题 - 因为它的使用只是在一个更好的条件下保持它在里面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2011-09-18
    • 2011-03-11
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多