如果要在多个地方导入Singleton类,该如何做?
我最终得到了这样的结果,但是每次导入时都导出一个new()实例(至少我认为是这样)。
class RenderToRootAPI {
renderToRootComponent = null
setRenderComponent = ref => this.renderToRootComponent = ref
setInstance = instance => {
console.warn('setting instance')
this.renderToRootComponent.setInstance(instance)
}
deleteInstance = () => this.renderToRootComponent.deleteInstance
}
export default new RenderToRootAPI()
最佳答案
您所写的内容将导出一个单例。导入多少次都没有关系。
如果您将其编写为以下示例,则可能看起来更加清晰:
class RenderToRootAPI {
renderToRootComponent = null
setRenderComponent = ref => this.renderToRootComponent = ref
setInstance = instance => {
console.warn('setting instance')
this.renderToRootComponent.setInstance(instance)
}
deleteInstance = () => this.renderToRootComponent.deleteInstance
}
const renderToRootAPI = new RenderToRootAPI();
export default renderToRootAPI;
该类甚至不会导出,并且单个导出的实例将在导入它的所有模块中使用。