尝试发送文档时无法读取未定义的属性'emit'

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

我正在尝试使用designPouchDB中的实体标签创建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函数?

先谢谢您。

reactjs pouchdb
1个回答
0
投票

我假设您的函数是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);
       });
     }
   }
};
© www.soinside.com 2019 - 2024. All rights reserved.