使用promise作为回调来实现setState [英] React setState with promise as a callback

查看:947
本文介绍了使用promise作为回调来实现setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Promise作为React中的回调尝试使用SetState时收到错误。这可能是由于我的错误,并希望对React中的设置状态做一些澄清。我收到的错误消息如下。

I received an error when trying to SetState using a Promise as a callback in React. This is likely due to an error on my part and would like some clarification on set State in React. The error message I am receiving is as follows.

错误:作为回调传递的参数无效。期望一个函数。而是收到:[object Promise]

ERR: "Invalid argument passed as callback. Expected a function. Instead received: [object Promise]"

我在下面重构了我的代码示例(编辑),试图向其他人提供使用。

I have refactored my code example below (edit) to try and provide use to others.

    this.setState({ value: v }, this.callAsync)

// Async function 

  callAsync = async () => {
    await this.props.foo({
    // Something async-y
   })
 .then(success => console.log(success)
 }


推荐答案

重新编写原始问题

this.setState({ value: v }, this.callAsync())

async 函数总是返回一个承诺,这当然不是一个回调。在你的情况下,该承诺以 undefined 因为你没有在 callAsync 中完成返回

An async function always returns a promise, which isn't (of course) a callback. In your case, that promise resolves with undefined as you haven't done a return in your callAsync.

如果您的目标是在状态更新完成后调用 callAsync ,则将调用包装在另一个函数中,例如:

If your goal is to call callAsync after the state update is complete, then wrap the call in another function, e.g.:

this.setState({value: v}, async () => {
    try {
        await this.callAsync();
    } catch (e) {
        // handle error
    }
});

this.setState({value: v}, () => {
    this.callAsync().catch(e => {
        // handle error
    });
});

请注意,处理潜在错误至关重要;否则,如果 this.props.foo 返回的承诺被拒绝,你将得到未处理的解决错误。

Note that it's essential to handle potential errors; otherwise, you'll get unhandled resolution errors if the promise returned by this.props.foo is rejected.

重新修改后的问题中的代码:

这只是的一个简单情况,这个不是你在回调中的预期,因为在这个问题的答案中详细描述了上面的解决方案也适用于此,方便;它是那里答案列出的解决方案之一。并且它正确处理错误,其他一些问题的答案(例如,使用 this.callAsync.bind(this))不会。

This is just a simple case of this not being what you expect in the callback, as described in detail in this question's answers. The solution above also works for that, conveniently; it's one of the solutions listed by the answers there. And it handles errors correctly, which some of the other answers to that question (using this.callAsync.bind(this) for instance) won't.

这篇关于使用promise作为回调来实现setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆