如果我们在 render 方法中调用异步函数会发生什么? [英] What happens if we call an async function inside render method?
本文介绍了如果我们在 render 方法中调用异步函数会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们不使用 redux 或 saga,而是使用服务来进行 API 调用和存储数据.考虑到有一个按钮会在单击时进行异步调用.
We do not use redux or saga and use services instead, for making API calls and storing data. Consider that there is a button that will make an async call when clicked.
- 在渲染方法中调用异步函数是否安全?
- 在 promise 得到解决之前,它是否会导致 UI 无响应?
render() {
return (
<Button onPress={() => {await this.requestOtp()}} text="Get OTP" />
);
}
推荐答案
尝试使用钩子:
import React, { useState } from 'react';
function MyComponent(){
let [output, updateOutput] = useState(null);
async function asyncFunction(){
// call here
let response = await this.requestOtp();
updateOutput(response.data);
}
return <Button onPress={asyncFunction} text={output} />
}
这篇关于如果我们在 render 方法中调用异步函数会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文