【问题标题】:Will using functions to render content hurt react performance?使用函数渲染内容会损害反应性能吗?
【发布时间】:2018-05-29 15:09:17
【问题描述】:

这篇文章(和其他地方)现在提到在渲染内部调用函数:

https://levelup.gitconnected.com/optimize-react-performance-c1a491ed9c36?ref=reddit

我一直对大型 React 类组件使用一种模式,我会将一些 JSX 从渲染函数移到方法中。这避免了有十亿个一次性使用的单独组件,还避免了在渲染区域内放置冗长的 if/then 或三元逻辑,我发现 稍微 难以阅读。

class HelpModal extends React.Component {
  state = { visible: false };

  renderContent = () => {
    if (this) {
      return <div />
    } 
    if (that) {
      return <span />
    }
  }
  render() {

    return (
      <Modal visible={this.state.visible}>
         {this.renderContent()}
      </Modal>
    );

  }
}

我在很多地方都看到过这种策略,但现在听起来,根据上面的博客文章,这在性能方面可能是一种不好的做法?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这取决于你如何使用内联函数。

    React 在 props 和/或 state 改变后调用渲染函数。每次他们改变渲染函数时都会被调用。

    如果您计算由于新的 props/state 值而没有改变的东西,那么这个内联函数确实会对您的应用性能产生负面影响。

    例子:

    render() {
        <div>
            { this.props.items.map(() => <SomeComponent />) }
        </div>
    }
    

    如果您在此处或其他任何地方计算它并不会改变您每次调用渲染函数时都需要计算它的事实。完全没有负面影响。

    computeStaticStuff(x, y) {
        return x + y > 0 ? <p /> : <i />;
    }
    
    render() {
        <div>
            { () => this.computeStaticStuff(5, 6) }
        </div>
    }
    

    这将是一个 ((n) 极其愚蠢的) 根本不需要的重新计算示例。

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 2011-01-10
      • 2013-08-15
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多