在react
狀態組件中state
定義方式分爲兩種,一種是在construcor
中定義;另外一種是在constructor
外面定義。網上有些人說state
屬性定義在constructor
裏面時,state
掛在組件實例上,定義在constructor
外面會掛在原型對象上。爲了方便分析兩種定義方式之間的區別,下面經過babel
轉譯到ES5
。react
這裏咱們採用babel7
版本git
cnpm i @babel/core @babel/cli @babel/preset-env @babel/preset-react -D
在項目根目錄下新建.babelrc
配置文件,babel
命令默認尋找該文件github
// .babelrc { presets: ["@babel/preset-env", "@babel/preset-react"] }
在package.json
添加指令腳本express
"scripts": { "babel": "babel ./demo3.jsx -o build.js" },
state在constructor裏面npm
import React from 'react' export default class App extends React.Component { constructor() { super() this.state = { count: 0 } } render() { return <div>{this.state.count}</div> } }
state在constructor外面json
安裝@babel/plugin-proposal-class-properties
,修改.babelrc
瀏覽器
{ "presets": ["@babel/preset-env", "@babel/preset-react"], "plugins": ["@babel/plugin-proposal-class-properties"] }
import React from 'react' export default class App extends React.Component { // 下面state寫法屬於ES7語法,目前瀏覽器還不支持,須要安裝@babel/plugin-proposal-class-properties,並在.babelrc中plugins屬性中配置 state = { count: 0 } render() { return <div>{this.state.count}</div> } }
state在constructor裏面babel
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var App = /*#__PURE__*/function (_React$Component) { _inherits(App, _React$Component); var _super = _createSuper(App); // Support for the experimental syntax 'classProperties' isn't currently enabled // Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation. function App() { var _this; _classCallCheck(this, App); _this = _super.call(this); _this.state = { count: 0 }; return _this; } _createClass(App, [{ key: "render", value: function render() { return /*#__PURE__*/_react["default"].createElement("div", null, this.state.count); } }]); return App; }(_react["default"].Component); exports["default"] = App;
state在constructor外面app
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var App = /*#__PURE__*/function (_React$Component) { _inherits(App, _React$Component); var _super = _createSuper(App); function App() { var _this; _classCallCheck(this, App); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "state", { count: 0 }); return _this; } _createClass(App, [{ key: "render", value: function render() { return /*#__PURE__*/_react["default"].createElement("div", null, this.state.count); } }]); return App; }(_react["default"].Component); exports["default"] = App;
轉義後導出規則採用的commonjs
,咱們寫一個index.js
導入App
來看看state
屬性在哪?函數
// index.js const App = require('./build.js').default // 獲得的是App構造函數 console.log(new App()) console.log(App.prototype)
state
定義在constructor
裏面打印結果
App { props: undefined, context: undefined, refs: {}, updater: { isMounted: [Function: isMounted], enqueueForceUpdate: [Function: enqueueForceUpdate], enqueueReplaceState: [Function: enqueueReplaceState], enqueueSetState: [Function: enqueueSetState] }, state: { count: 0 } } App {}
state
定義在constructor
外面打印結果
App { props: undefined, context: undefined, refs: {}, updater: { isMounted: [Function: isMounted], enqueueForceUpdate: [Function: enqueueForceUpdate], enqueueReplaceState: [Function: enqueueReplaceState], enqueueSetState: [Function: enqueueSetState] }, state: { count: 0 } } App {}
咱們看到這兩種定義方式轉義後打印結果是同樣的,state
屬性都是掛在組件實例上。