我有一个 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 中使用单例的最佳方法是将其附加到 window 对象。只需确保您首先将单例附加到一个对象,该对象又附加到窗口对象 - 以避免污染您的窗口命名空间。您只需在启动脚本中执行一次此附加操作:
index.js
var window.app = {}
window.app.authentication = (function() {
function authenticateUser(userId) {
}
return {
authenticateUser: authenticateUser
}
})();
然后在您想要使用它的其他模块中:
登录.js
window.app.authentication.authenticateUser("johndoe");
关于javascript - 我应该导出单例类以在 React 中使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884826/