Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

提升 React 函数组件 45% 的性能 #7

Open
justjavac opened this issue Nov 14, 2017 · 0 comments
Open

提升 React 函数组件 45% 的性能 #7

justjavac opened this issue Nov 14, 2017 · 0 comments
Labels

Comments

@justjavac
Copy link
Contributor

今日阅读:45% Faster React Functional Components, Now

预计阅读时间为 1 分钟。


很多时候对于非常简单的组件,我们通常使用函数组件

// 一个简单的函数组件
const Avatar = (props) => {
  return <img src={props.url} />;
}

但是函数组件也是一个 React 组件,当使用时,也会在内部调用 componentWillMountcomponentDidMountcomponentWillUnmount 等声明周期函数。

为了提示性能,我们可以把它作为 JavaScript 函数使用,而不是作为 React 组件。

 ReactDOM.render(
   <div>
-    <Avatar url={avatarUrl} />   // <--- 作为 React 组件使用
+    {Avatar({ url: avatarUrl })} // <--- 作为 JavaScript 函数使用
     <div>{commentBody}</div>
   </div>,
   mountNode
 );

 // 编译后的 JavaScript 代码
 ReactDOM.render(React.createElement(
   'div',
   null,
-  React.createElement(Avatar, { url: avatarUrl }), // <--- 作为 React 组件使用
+  Avatar({ url: avatarUrl }),                      // <--- 作为 JavaScript 函数使用
   React.createElement(
     'div',
     null,
     commentBody
   )
 ), mountNode);

改成函数调用后,没有生成 React.createElement,也就没有了 React 组件的生命周期函数。

继续阅读:45% Faster React Functional Components, Now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant