简体   繁体   English

我应该导出单例类以在 React 中使用吗?

[英]Should I export singleton class for consumption in React?

I have an AuthService class that provides all the api calls and handles authentication for those calls, so its a nice modular service.我有一个 AuthService 类,它提供所有 api 调用并处理这些调用的身份验证,因此它是一个很好的模块化服务。 It is not a React component and not used in any render calls.它不是 React 组件,不用于任何渲染调用。 It handles fetch calls mostly.它主要处理提取调用。 In many other classes now, I use a single global instance of this class, and import it at the top.现在在许多其他类中,我使用此类的单个全局实例,并将其导入顶部。

I don't think a context is the right approach because it's not an object type or used in renders.我认为上下文不是正确的方法,因为它不是对象类型或用于渲染。 I use the instance in componentDidMount() and useEffect().我在 componentDidMount() 和 useEffect() 中使用实例。

an example:一个例子:

//at the bottom, outside curly braces defining AuthService
export const Auth = new AuthService();

a consumer:一个消费者:

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>

);
}

I think the best approach to using singletons in React is by attaching it to the window object.我认为在 React 中使用单例的最佳方法是将其附加到窗口对象。 Just make sure you first attach the singleton to an object, which in turn is attached to the window object - to avoid polluting your window namespace.只需确保首先将单例附加到一个对象,该对象又附加到窗口对象 - 以避免污染您的窗口名称空间。 You would do this attaching in your startup script only once:您只需在启动脚本中附加一次即可:

index.js索引.js

var window.app = {}
window.app.authentication = (function() {
   function authenticateUser(userId) {

   }

   return {
      authenticateUser: authenticateUser
   }
})();

Then in some other module where you want to use it:然后在您要使用它的其他模块中:

Login.js登录.js

window.app.authentication.authenticateUser("johndoe");

It's just fine.没关系。 There's nothing wrong.没有错。 But why use same instance for everything?但是为什么对所有东西都使用相同的实例呢?

new AuthService()

I would recommend you to export AuthService .我建议您导出AuthService Then, whenever you'll need to use that service, define a new instance and use:然后,每当您需要使用该服务时,定义一个新实例并使用:

const Auth = new AuthService()
// now, use Auth

It's just a personal choice.这只是个人选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM