![](/img/trans.png)
[英]Should I be using a Class or an Object Literal when implementing a singleton in JS?
[英]Should I export singleton class for consumption in React?
我有一个 AuthService 类,它提供所有 api 调用并处理这些调用的身份验证,因此它是一个很好的模块化服务。 它不是 React 组件,不用于任何渲染调用。 它主要处理提取调用。 现在在许多其他类中,我使用此类的单个全局实例,并将其导入顶部。
我认为上下文不是正确的方法,因为它不是对象类型或用于渲染。 我在 componentDidMount() 和 useEffect() 中使用实例。
一个例子:
//at the bottom, outside curly braces defining AuthService
export const Auth = new AuthService();
一个消费者:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { useState, useEffect } from 'react';
import CommentList from "./CommentList";
import CommentForm from "./CommentForm";
import Comment from "./Comment";
import AuthService from './AuthService';
import { Auth } from './AuthService';
export default function CommentBox(props) {
const [comments, setComments] = useState([]);
// const Auth = new AuthService();
const [formText, setFormText] = useState('');
const [update, setUpdate] = useState(false);
useEffect(() => {
Auth.fetch('/comments/get_comment_for_bill/' + props.id + '/').then((data) => {
if (typeof data[0] !== 'undefined') {
setComments(data);
} else {
setComments([]);
}
setUpdate(false);
});
return () => {
return;
}
}, [props, update]);
return (
<div >
<CommentList comments={comments}/>
<CommentForm id={props.id} formText={formText} setFormText={setFormText} setUpdate={setUpdate}
onChange={e => {
setFormText(e.target.value);
}} />
</div>
);
}
我认为在 React 中使用单例的最佳方法是将其附加到窗口对象。 只需确保首先将单例附加到一个对象,该对象又附加到窗口对象 - 以避免污染您的窗口名称空间。 您只需在启动脚本中附加一次即可:
索引.js
var window.app = {}
window.app.authentication = (function() {
function authenticateUser(userId) {
}
return {
authenticateUser: authenticateUser
}
})();
然后在您要使用它的其他模块中:
登录.js
window.app.authentication.authenticateUser("johndoe");
没关系。 没有错。 但是为什么对所有东西都使用相同的实例呢?
new AuthService()
我建议您导出AuthService
。 然后,每当您需要使用该服务时,定义一个新实例并使用:
const Auth = new AuthService()
// now, use Auth
这只是个人选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.