【问题标题】:Are React functional components really more lightweight than class components?React 函数式组件真的比类组件更轻量级吗?
【发布时间】:2019-10-04 07:57:50
【问题描述】:

我在a few places 中读到,函数式组件比类组件更轻量级,从here 看来,Facebook 打算让函数式 + 挂钩成为新组件的首选范例。

我看到的问题是,对于函数式组件,诸如类方法之类的东西会在每次渲染时重新定义,而不仅仅是一次。这不是一个问题,还是功能组件的其他优势远远超过这个?


示例:

类组件

class SignInForm extends React.Component {
  ...
  // Only gets defined when the component is created with `React.createElement`
 submit = () => {
    // send POST request to get an auth token, etc.
  }

  render() {
    <form>
      ...
      <button onClick={this.submit}>Sign In</button>
    </form>
  }
}

功能组件

function SignInForm (props) {
  ...
  // Gets defined on every render, since this essentially *is* the `render` function
  const submit = () => {
    // send POST request to get an auth token, etc.
  }

  return (
    <form>
      ...
      <button onClick={submit}>Sign In</button>
    </form>
  );
}

【问题讨论】:

  • @PatrickRoberts 类主体中定义的方法(在这种情况下通常是生命周期或回调方法)。
  • @PatrickRoberts 我编辑了问题以澄清我的意思。
  • 对于功能性(无状态)组件,如果参数未更改,则无需调用渲染函数。类需要维护状态,因此相同的输入并不能保证相同的输出,导致渲染函数必须更频繁地调用

标签: javascript reactjs react-hooks react-component


【解决方案1】:

网络应用程序中的Slowest 部分是rendering。所以在每次渲染上创建一个新函数并不是什么大问题。同样对于 Web 应用程序,build size 很重要,对于功能组件,缩小比基于类的组件更有效。

随着memouseMemouseCallback 等新功能的发布,我们可以获得与使用基于类的组件相同的性能。

React 社区正在朝着函数式组件和钩子的方向发展,这表明函数式组件还不错。

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2012-11-25
    • 2021-02-25
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多