这在Babel编译的方法中是未定义的

时间:2015-03-29 04:01:08

标签: reactjs webpack babeljs

我试图用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 变量引用的是对象文字,而不是。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

实际上并不是问题所在。它是this未定义的,因为您没有绑定更新功能。

您可以在constructor或渲染中执行此操作。大多数人都是在渲染中完成的。

<div onClick={this.update.bind(this)} />

或(我的偏好),一个保留this的箭头功能。

<div onClick={() => this.update()} />