我创建了一个CodeSandbox 上的示例我认为重现了你的问题,尽管我不确定。如果没有,请创建您自己的示例。相关代码包含在下面。
在此示例中,代码运行良好。console.log(this, "hello")
logs a Square
正如你所期望的,对象+“你好”。如果你在let y = 2 + 2
行,Chrome 调试器将显示
this: undefined
x: 2
y: undefined
当然,y
是未定义的,因为let y
语句尚未执行。x
已定义,如预期的那样。this
是未定义的,因为 React 和 Babel 在幕后跳过了很多圈子,并且this
事实上,是未定义的。如果您想访问this
从调试器中,您需要使用_this
。事实上,即使你在线上放置了一个断点let y = 2 + 2
,这不是正在执行的实际源代码或实际断点所在的位置。您所看到的是由源图它允许您查看并在您编写的代码上设置断点,尽管实际运行的代码完全不同(Babel 等处理的结果)。
我写的代码是:
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null
};
}
click = () => {
console.log(this, "hello");
let x = 1 + 1; //This is just here to let chrome put a break point here.
let y = 2 + 2; //This is just here to let chrome put a break point here.
};
render() {
return (
<button className="square" onClick={this.click}>
{this.props.value}
</button>
);
}
}
实际运行的代码是:
var Square =
/*#__PURE__*/
function (_React$Component) {
(0, _inherits2.default)(Square, _React$Component);
function Square(props) {
var _this;
(0, _classCallCheck2.default)(this, Square);
_this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Square).call(this, props));
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)), "click", function () {
console.log((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)), "hello");
var x = 1 + 1; //This is just here to let chrome put a break point here.
var y = 2 + 2; //This is just here to let chrome put a break point here.
});
_this.state = {
value: null
};
return _this;
}
(0, _createClass2.default)(Square, [{
key: "render",
value: function render() {
return _react.default.createElement("button", {
className: "square",
onClick: this.click
}, this.props.value);
}
}]);
return Square;
}(_react.default.Component);
由于 React.js 的内部结构(特别是它包装事件的方式),在调用处理程序时,this
未定义。如果你查看调用堆栈,你会发现executeDispatch
calls invokeGuardedCallbackAndCatchFirstError
明确值为undefined
为了context
对象最终的价值this
在回调里面。当你编写代码时,React 和 Babel 会尝试向你隐藏所有这些,但它们无法完全向调试器隐藏这些,特别是在以下方面:this
,所以这种情况你得去实际的代码中看看需要参考_this
在调试器中。