使用promise作为回调来实现setState [英] React setState with promise as a callback
问题描述
我在使用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 $ c $结算c>因为你没有在
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屋!