我试图用React 0.13和ES6语法编写一个小型webapp。我使用webpack和babel-loader编译:
loaders: [
{ test: /\.js/, exclude: /node_modules/, loader: "babel-loader"}
]
我在方法中遇到这个变量有问题,得到"这是未定义的"在我的代码中的几个地方。例如:
export class PanelEditor extends React.Component {
...
update (){
if (!this.isMounted())
return;
this.setState(this.getStateFromStore());
}
...
}
在这种情况下,永远不应该定义这个变量。但是,我发现问题可能是Babel重写代码的方式:
update: {
value: function update() {
if (!this.isMounted()) {
return;
}
this.setState(this.getStateFromStore());
}
},
以这种方式,在我看来, this 变量引用的是对象文字,而不是类。我该如何解决这个问题?
答案 0 :(得分:5)
实际上并不是问题所在。它是this
未定义的,因为您没有绑定更新功能。
您可以在constructor
或渲染中执行此操作。大多数人都是在渲染中完成的。
<div onClick={this.update.bind(this)} />
或(我的偏好),一个保留this
的箭头功能。
<div onClick={() => this.update()} />