【问题标题】:Can't seem to return from catch promise似乎无法从捕捉承诺中恢复过来
【发布时间】:2019-04-28 08:18:45
【问题描述】:

我正在尝试从我的 PouchDB 数据库中填充一个菜单列表,但我似乎无法从我在数据库上调用 get 后调用的 promise 中返回任何内容。

这是我的代码:

<MenuList>
   {this.populateSavedClues()}
</MenuList>
.
.
.
populateSavedClues() {
    var db = this.db;
    db.get('roomClues').then(function (doc) {
        if (doc.clues == null || doc.clues == array()) {
          return <MenuItem onClick={() => this.handleClose()} align='start' size='small' >You have no saved clues for this room</MenuItem>;
        }
        else {
          return doc.clues.map((clue) => <MenuItem onClick={() => this.selectClue(clue)} align='start' size='small' >{clue}</MenuItem>);
        }
    }).catch(function (err) {
        if(err.name=="not_found") {
          return <MenuItem onClick={() => this.handleClose()} align='start' size='small' >You have no saved clues for this room</MenuItem>;
        }
    });
  }

现在我正在专门测试捕获条件。我知道它击中了我的测试中未找到的事实,并在其中击中了该返回语句,但我的菜单没有任何项目并且仍然是空的。我已经在承诺之外进行了测试,只是让这个函数在没有其他逻辑的情况下返回菜单项,这也有效,所以它试图在 catch 承诺内返回,我正在努力弄清楚为什么返回不会一直到 MenuList 调用。我需要做什么才能返回菜单项?

【问题讨论】:

  • 只是一个旁注..如果你使用 onClick={ () => { this.someMethod() } } 你可以简单地把它写成 onClick={this.someMethod()} - 这样您不会在渲染每个函数调用时创建匿名函数。
  • @noa-dev 这并不完全正确。首先需要跳过括号,例如onClick={this.someMethod}。其次,如果方法没有绑定到组件实例,它会被错误的上下文触发,所以方法内部的this 是不正确的。在 onClick 内部使用箭头函数实际上是一种保留组件上下文的方法。
  • 是的,很抱歉忘记删除 ()。想知道匿名箭头函数如何保留上下文,因为它默认从其包装范围继承上下文。

标签: javascript reactjs promise material-ui pouchdb


【解决方案1】:
renderMenu() {
        let jsx;
        if (this.state.clues.length == 0) {
            jsx = <MenuItem onClick={() => this.handleClose()} align='start' size='small' >You have no saved clues for this room</MenuItem>
        } else {
            jsx = this.state.clues.map((clue) => {
                return <MenuItem onClick={() => this.selectClue(clue)} align='start' size='small' >{clue}</MenuItem>
            })
        }

        return jsx;
    }

    async populateSavedClues() {
        var db = this.db;
        try {
            const doc = await db.get('roomClues');
            return doc;         

        } catch (error) {
            alert('Error fetching clues...')
        }
    }



async componentDidMount() {

        const doc=  await this.populateSavedClues();

        this.setState({ clues: doc.clues });
    }

在你的 JSX 中:

<MenuList>
   {this.renderMenu()}
</MenuList>

请记住在您的状态中放置一个“线索”(空数组)属性。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2018-08-24
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2017-03-15
    • 2019-11-06
    相关资源
    最近更新 更多