我应该在React中导出单身类消费吗?

问题描述 投票:0回答:1

我有一个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>

);
}
javascript reactjs singleton
1个回答
0
投票

没关系。没有错。但为什么要使用相同的实例?

new AuthService()

我建议你出口AuthService。然后,每当您需要使用该服务时,请定义一个新实例并使用:

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

这只是个人选择。

© www.soinside.com 2019 - 2024. All rights reserved.