繁体   English   中英

React 或 CRA 是否优化 static 语句? 如何防止 static 语句得到优化?

[英]Does React or CRA optimize static statement? How to prevent static statement from getting optimized?

让我们考虑以下代码片段,它是从React 教程演示计算器修改而来的。 分别在赋值语句之前放置了两个日志记录调用。

export default class Button extends React.Component {
  // <= The newly added content
  static propTypes = (console.log("static statement executed"), {. 
    name: PropTypes.string,
    orange: PropTypes.bool,
    wide: PropTypes.bool,
    clickHandler: PropTypes.func,
  });
  // <= The newly added content
  member = (console.log("normal statement executed"), 1);  

  handleClick = () => {
    this.props.clickHandler(this.props.name);
  };

  render() {
    const className = [
      "component-button",
      this.props.orange ? "orange" : "",
      this.props.wide ? "wide" : "",
    ];

    return (
      <div className={className.join(" ").trim()}>
        <button onClick={this.handleClick}>{this.props.name}</button>
      </div>
    );
  }
}

在执行npm run build并检查build/static/下的工件后,我发现与 static 分配相关的第一个日志记录语句消失了,而第二个则保留了。 此外,查看页面的浏览器控制台确实记录了第二条消息,但没有记录第一条消息。 在此处输入图像描述

所以我想知道 React 或 CRA 是否优化了任何 static 语句? 如果是这样,如何防止这样的语句得到优化?

如果您正在创建生产版本,我相信 propTypes 已被剥离。 在这里你可以看到 CRA 的变化。 使用的插件是babel-plugin-transform-react-remove-prop-types 因此,为什么您的第二个语句正在评估而不是 propTypes 下的那个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM