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

Ger*_*rdo 3 reactjs webpack babeljs

我正在尝试使用React 0.13和ES6语法编写一个小型webapp.我正在使用webpack和babel-loader来编译:

loaders: [
  { test: /\.js/, exclude: /node_modules/, loader: "babel-loader"}
]
Run Code Online (Sandbox Code Playgroud)

我在方法中遇到了这个变量的麻烦,在我的代码中的几个地方都得到了"这是未定义的".例如:

export class PanelEditor extends React.Component {
  ...
  update (){
    if (!this.isMounted())
      return;

    this.setState(this.getStateFromStore());
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

这个变量不应该这样的条件下是不确定的.但是,我发现问题可能是Babel重写代码的方式:

update: {
  value: function update() {
    if (!this.isMounted()) {
      return;
    }
    this.setState(this.getStateFromStore());
  }
},
Run Code Online (Sandbox Code Playgroud)

就这样,在我看来,这个变量引用了对象文字而不是.我怎样才能解决这个问题?

Bri*_*and 5

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

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

<div onClick={this.update.bind(this)} />
Run Code Online (Sandbox Code Playgroud)

或者(我的偏好),保留的箭头功能this.

<div onClick={() => this.update()} />
Run Code Online (Sandbox Code Playgroud)

  • (而对于真正的"为什么",当使用`class`语法而不是`React.createClass`时,React团队决定不提供使用新方法进行自动绑定的方法:http:// facebook .github.io /反应/博客/ 2015/1月27日/反应-v0.13.0-β-1.HTML#自动绑定) (3认同)