我正在尝试使用design
为PouchDB
中的实体标签创建ReactJS
。我设法使用put
函数保存了设计,但是当我查询设计时,响应只是一个空数组,并且在控制台中出现以下错误:
TypeError: Cannot read property 'emit' of undefined
我认为问题出在我的函数中,以后我将其用作设计变量的映射参数:
function emitTagsMap(doc)
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};
this.db
在构造函数中声明:
constructor(service, name)
{
if (!service || !name) throw new Error("PouchDatabase initialized incorrectly");
this.name = name;
this.db = new PouchDB(name);
this.service = service;
this.tagsView();
}
[请记住我对PouchDB
完全陌生。
任何想法如何初始化emit
函数?
先谢谢您。
我假设您的函数是JavaScript类的一部分(否则,您必须用this
解释这个想法)。在ES6中,您必须将this
绑定到常规函数。您有两个选择:
首先-通过构造函数将其绑定:
constructor() {
this.emitTagsMap = this.emitTagsMap.bind(this);
}
第二个-将该功能声明为箭头一。这样,react会为您绑定它:
function emitTagsMap = (doc) =>
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};