实际上我对原生反应还很陌生,我正在调用一个单例类中的javascript函数。我想从constructor.But的另一个react本机组件调用此函数,如果我尝试调用,它不会调用该函数。
代码:
export default class CustomScreen extends React.Component {
constructor(){
LoginUtil.getInstance().getLoginToken() // ==> not working
}
}
export default class LoginUtil {
static instance = null;
static createInstance() {
var object = new LoginUtil();
return object;
}
static getInstance () {
if (!LoginUtil.instance) {
LoginUtil.instance = LoginUtil.createInstance();
}
return LoginUtil.instance;
}
getLoginToken(){
return "token"
}
}
发布于 2020-10-27 14:28:50
在JavaScript中实现单例模式的方式是利用导出
如下所示:
// LoginUtils.js
class LoginUtil {
constructor() {
// Only called once
this.token = 'initial';
}
setLoginToken(token) {
this.token = token;
}
getLoginToken(){
return this.token;
}
}
export default new LoginUtil();
诀窍是,在导出实例时,它将处理单个实例,并避免编写用于实例化的样板代码。
然后在您的组件文件中执行以下操作:
import loginUtils from './LoginUtils';
export default class CustomScreen extends React.Component {
constructor(){
const token = loginUtils.getLoginToken()
}
}
编辑:
你可能无法工作的原因是因为你需要在你的组件构造函数中添加super()
作为第一个语句:
class CustomScreen extends React.Component {
constructor(){
super();
LoginUtil.getInstance().getLoginToken();
}
...
}
class CustomScreen extends React.Component {
constructor(){
super()
this.state = { token: LoginUtil.getInstance().getLoginToken() };
}
render() {
return <p>Token: {this.state.token}</p>
}
}
class LoginUtil {
static instance = null;
static createInstance() {
var object = new LoginUtil();
return object;
}
static getInstance () {
if (!LoginUtil.instance) {
LoginUtil.instance = LoginUtil.createInstance();
}
return LoginUtil.instance;
}
getLoginToken(){
return "token-test"
}
}
ReactDOM.render(<CustomScreen />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
发布于 2020-10-27 14:16:35
不是从单例文件中导出类,而是导出其对象,如下所示:
export default new LoginUtil()
然后导入此对象并调用该类的任何函数
https://stackoverflow.com/questions/56933270
复制