我试图在我的 Next.js 应用程序中拥有动态导入模块的 Singleton 实例。但是,我当前的实现似乎每次调用 getInstance
时都会初始化一个新实例。
这是 gui.js
中的实现:
let dynamicallyImportPackage = async () => {
let GUI;
await import('three/examples/jsm/libs/dat.gui.module.js')
.then(module => {
GUI = module.GUI
})
.catch(e => console.log(e))
return GUI;
}
let GUI = (function () {
let instance;
return {
getInstance: async () => {
if (!instance) {
let GUIModule = await dynamicallyImportPackage();
instance = new GUIModule();
}
return instance;
}
};
})();
export default GUI;
我使用 GUI.getInstance().then(g => { ... }) 在 ES6 类函数中调用它
我通常会使用 React Context API 或 Redux 来实现这种共享状态,但对于这种情况,我需要它纯粹在 ES6 JS 中而不是 React 中。
最佳答案
您需要缓存 promise ,而不是实例,否则它将在第一个仍在加载且尚未分配 instance
变量时尝试再次导入模块(并实例化另一个实例) .
async function createInstance() {
const module = await import('three/examples/jsm/libs/dat.gui.module.js')
const { GUI } = module;
return new GUI();
}
let instancePromise = null;
export default function getInstance() {
if (!instancePromise) {
instancePromise = createInstance()
// .catch(e => {
// console.log(e); return ???;
// instancePromise = null; throw e;
// });
}
return instancePromise;
}
关于javascript - Next.js 中动态导入模块的单例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65484251/