![](/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.