【问题标题】:What happens if we call an async function inside render method?如果我们在 render 方法中调用异步函数会发生什么?
【发布时间】:2019-12-04 00:30:55
【问题描述】:

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

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

【问题讨论】:

  • 您没有在渲染函数中调用异步方法。在onPress回调中调用,应该没问题。
  • @zero298 这个问题的标题看起来像骗子,但它真的不是骗子,除非OP更改代码。

标签: javascript reactjs react-native async-await


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试使用钩子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2012-01-13
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多