当我单击“后退”按钮时,我的Uppy表单会被短暂加载两次。当我离开页面时,我怎样才能获得关闭上一个Uppy实例的刺激?
在Uppy之后,我希望类似这样的东西(下面的代码),但是我得到了错误:uppy is nil or undefined on disconnect()。
我如何将uppy.close()绑定到Uppy的原始实例?
import { Controller } from "@hotwired/stimulus"
import Uppy from "@uppy/core"
export default class extends Controller {
connect() {
const uppy = new Uppy()
}
disconnect() {
// This causes an error
uppy.close();
}
}发布于 2022-07-27 20:48:11
问题是,您试图将uppy作为在connect方法中设置的局部变量访问。但是,获得对其他方法范围的访问的方法,这就是为什么在尝试在uppy方法中访问它时未定义它的原因。
相反,你有一些选择。
选项1-将变量存储在类实例上
每个类实例都有自己的this变量,您可以轻松地在其上存储值,因为它是一个对象。
按照惯例,下面的示例使用this._uppy (带有下划线),但任何名称都可以。
import { Controller } from "@hotwired/stimulus";
import Uppy from "@uppy/core";
export default class extends Controller {
connect() {
// 'store' the uppy instance against your class instance
this._uppy = new Uppy();
}
disconnect() {
// read the instance and access its close method
this._uppy.close();
}
}选项2-全局存储变量
考虑这一点的另一种方法是,如果已经创建了一个新的Uppy实例,则不希望创建一个新的实例。
您可以将这个实例存储在window上,尽管这打破了文件是一个独立模块的概念。
另一种方法是将实例存储在模块文件本身中,这可能会为单元测试创建一些边缘问题,但请看您如何处理。
import { Controller } from "@hotwired/stimulus";
import Uppy from "@uppy/core";
// declare a variable in the 'module' scope (this file).
let uppy;
export default class extends Controller {
connect() {
// if uppy has already been instantiated - do not create a new one
if (uppy) return;
// 'store' the uppy instance against your module scoped global variable
uppy = new Uppy();
}
disconnect() {
// read the instance and access its close method
uppy && uppy.close();
// reset the variable to null
uppy = null;
}
}https://stackoverflow.com/questions/73126944
复制相似问题