首页 > 解决方案 > React 渲染箭头函数性能

问题描述

我正在阅读几篇文章,这些文章建议不要在 JSX 属性中使用箭头函数,如 onClick、onMouseMove 等。

https://reactjs.org/docs/faq-functions.html#is-it-ok-to-use-arrow-functions-in-render-methods

但是当谈到 JSX 中箭头函数的使用对性能的影响时。以下用于渲染 x & y & z 的方法是否存在差异。一般推荐哪种方法?

示例: https ://codesandbox.io/s/different-ways-to-create-react-components-sm517

const x = [1, 2, 3, 4, 5];
const y = [6, 7, 8, 9, 10];
const z = [11, 12, 13, 14, 15];
class MyComponent2 extends React.Component {
  showY = () => {
    return y.map(val => {
      return <p>{val}</p>;
    });
  };
  render() {
    const zValues = z.map(val => {
      return <p>{val}</p>;
    });
    return (
      <div>
        <div>
          <p>React Component Using a Class</p>
          {x.map(val => {
            return <p>{val}</p>;
          })}
        </div>
        <div>{this.showY()}</div>
        <div>{zValues}</div>
      </div>
    );
  }
}

标签: javascriptreactjsperformance

解决方案


如果您将使用箭头或简单功能,这没有区别。关于这两种声明函数的方式的所有规则在 javascript 中都是真实有效的。因此,您有权使用一种或另一种功能。


推荐阅读