[英]Access static variable from another class in React-Native app?
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.在另一个类中,我试图访问此 currentUser 的设置值。 I cannot figure out how to correctly call this function;我不知道如何正确调用这个函数; I am getting the error User.getCurrentUser is not a function
.我收到错误User.getCurrentUser is not a function
。 Should I be calling this function in a different way?我应该以不同的方式调用这个函数吗?
var User = require('./User');
getInitialState: function() {
var user = User.getCurrentUser();
return {
user: user
};
},
You are mixing import
/ export
styles.您正在混合import
/ export
样式。 You should either change your import to您应该将导入更改为
var User = require('./User').default
or或
import User from './User'
Or change your export:或更改您的导出:
module.exports = User
I think you also forgot the this keyword 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());
Try arrow function:尝试箭头函数:
class User {
static currentUser = null;
static getCurrentUser = () => {
return currentUser;
}
}
export default User;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.