简体   繁体   English

如何在函数外使用变量

[英]How to use a variable outside the function

I have this code in React Native: 我在React Native中有以下代码:

inApp1.get('isFullVersionBought').then((data) => {
    console.log(data);
    let fullversionbought = data;
});

How i can use fullversionbought variable outside this function? 我如何在此函数之外使用fullversionbought变量? Thanks. 谢谢。

You have to define the variable outside of the function, not inside as it is in your code sample. 您必须在函数外部定义变量,而不是在代码示例中定义变量。

var fullversionbought;
inApp1.get('isFullVersionBought').then((data) => {
    console.log(data);
    fullversionbought = data;
});

Javascript uses lexical scope at compile time. Javascript在编译时使用词法作用域。

Define the variable "fullbersionbought" outside the function first, then assign its value from within the function. 首先在函数外部定义变量“ fullbersionbought”,然后在函数内部分配其值。

The keyword "let", by its very definition, means scope the variable as block local. 顾名思义,“ let”一词的含义是将变量的作用域限定为局部块。 They only persist while that particular function is running. 它们仅在该特定功能运行时持续存在。

You can not use local variables out side the function.Thats why we have instance variables. 您不能在函数外使用局部变量,这就是为什么我们有实例变量的原因。

Add an instance variable to that class and fill the data in this function 向该类添加一个实例变量,并在此函数中填充数据

The variable will be useless until it gets the data. 该变量在获取数据之前将是无用的。 To avoid waiting for the variable to be populated, I would recommend to use a component state. 为了避免等待变量被填充,我建议使用组件状态。 In that case, once you receive the data, you will update the state of the component: 在这种情况下,一旦收到数据,您将更新组件的状态:

constructor() {
  this.state = {
    fullversionbought: {}
  };

  this.getData():
}

getData() {
inApp1.get('isFullVersionBought').then((data) => {
    this.setState({
      fullversionbought: data
    });
});
}

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

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