如果我们在render方法中调用异步函数会怎样?

时间:2019-07-25 16:55:00

标签: javascript reactjs react-native async-await

我们不使用redux或saga,而是使用服务来进行API调用和存储数据。考虑到有一个按钮,单击后将进行异步调用。

  1. 在render方法中调用async函数安全吗?
  2. 在答应得到解决之前,是否会使UI无响应?
render() {
    return (
        <Button onPress={() => {await this.requestOtp()}} text="Get OTP" />
    );
}

2 个答案:

答案 0 :(得分:0)

尝试使用钩子:

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} />

}

答案 1 :(得分:0)

渲染不能异步,您可以将异步传递给componentDidMount或使用钩子