Javascript 从 React-Native 应用程序中的另一个类访问静态变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37517822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:25:48  来源:igfitidea点击:

Access static variable from another class in React-Native app?

javascriptfunctionclassreact-native

提问by user3802348

in my react-native app I currently have a User class in which I define a current user as below:

在我的本机应用程序中,我目前有一个 User 类,我在其中定义了一个当前用户,如下所示:

class User {
    static currentUser = null;

    //other relevant code here

    static getCurrentUser() {
        return currentUser;
    }
}

export default User;

In a different class, I am trying to access the set value of this currentUser. I cannot figure out how to correctly call this function; I am getting the error User.getCurrentUser is not a function. Should I be calling this function in a different way?

在另一个类中,我试图访问此 currentUser 的设置值。我不知道如何正确调用这个函数;我收到错误User.getCurrentUser is not a function。我应该以不同的方式调用这个函数吗?

var User = require('./User');

getInitialState: function() {

    var user = User.getCurrentUser();

    return {
        user: user
    };


},

采纳答案by Balázs édes

You are mixing import/ exportstyles. You should either change your import to

你正在混合import/export风格。您应该将导入更改为

var User = require('./User').default

or

或者

import User from './User'

Or change your export:

或更改您的导出:

module.exports = User

回答by FlorianE

I think you also forgot the thiskeyword for returning the static "currentUser" field:

我认为您还忘记了返回静态“currentUser”字段的this关键字:

class User {
  constructor() {}

  static currentUser = {
    uname: 'xxx',
    firstname: 'first',
    lastname: 'last'
  };

  static getCurrentUser() {
    return this.currentUser;
  }
}

console.log(User.getCurrentUser());

回答by OAslan

Try arrow function:

尝试箭头函数:

class User {
    static currentUser = null;

    static getCurrentUser = () => {
        return currentUser;
    }
}
export default User;