繁体   English   中英

函数引用未定义的本地对象React

[英]Function reference undefined local object React

我有一个带有一些局部变量和方法的React组件。 方法的声明顺序并不重要(?),因为它们可以在任何我想从声明的组件中调用的地方使用。

但是,当我尝试在局部变量中引用方法时,如果在局部变量下声明了该方法,则会给出未定义的信息,为什么? 例:

//THIS WORKS

someFunction = () => {
  //some logic
}

localVariable = [
  {name: 'test', myFunction: this.someFunction},
  {name: 'test2', myFunction: this.someFunction}
}

//console.log(localVariable) gives 'function' at 'myFunction' key

//THIS DOES NOT WORK

localVariable = [
  {name: 'test', myFunction: this.someFunction},
  {name: 'test2', myFunction: this.someFunction}
}

someFunction = () => {
  //some logic
}

//console.log(localVariable) give 'undefined' at 'myFunction' key

//but also if I pass do not pass only the reference it works

localVariable = [
  {name: 'test', myFunction: () => this.someFunction()},
  {name: 'test2', myFunction: () => this.someFunction()}
}

someFunction = () => {
  //some logic
}

请参考以下链接,

http://javascript.info/function-expressions-arrows

当您使用箭头函数语法创建someFunction时,实际上您正在制作的变量等于分配给它的函数。

因此,当您定义局部变量时,它不会获得未定义的引用。

这是函数声明和函数作为表达式的问题。

函数表达式在执行到达时创建,并且从那时起可用。

您可以尝试在组件的类构造函数中设置localVariable

class YourClassName extends React.Component {
  constructor(props) {
    super(props);
    this.localVariable = [
      {name: 'test', myFunction: this.someFunction},
      {name: 'test2', myFunction: this.someFunction}
    ]
  }
  someFunction = () => {
    // logic...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM