在反应渲染中使用异步和等待

时间:2019-08-05 09:57:11

标签: javascript reactjs react-native

我试图在react native中捕捉状态栏的最高点。

我为此编写了以下代码

def copia(frase):
    return ''.join(c if c.isalpha() else " " for c in frase)

在这里,render() { let StatusBarHeight = null if (Platform.OS === 'ios') { StatusBarHeight = StatusBarManager.getHeight((statusBarHeight)=>{ console.log(statusBarHeight) return statusBarHeight }) console.log(`This is the height of the status bar in iOS:`,StatusBarHeight) } } 就是我打算存储在console.log(statusBarHeight)的{​​{1}},但是之后的第二个console.log给了我未定义的

{height: 44}

这使我认为StatusBarHeightconsole.log(`This is the height of the status bar in iOS:`,StatusBarHeight) 函数。因此,有人可以帮我弄清楚身高吗,我们如何在反应本机的渲染中使用异步等待

2 个答案:

答案 0 :(得分:2)

永远不要在渲染函数中使用异步函数,因为它会阻塞渲染,并且应该始终响应并且不阻塞整个应用程序,如果延迟渲染函数,则会发生这种情况。在状态中保存您的statusBarHeight,并在render函数中对其进行访问,并仅在外部更改(例如componentDidUdpate)时对其进行更新。

第二个console.log返回undefined,因为render不等待promise(StatusBarManager.getHeight)解析,而是立即执行render函数。兑现承诺后,您会看到另一个带有statusBarHeight的console.log。因此,从本质上讲,没有,您不能也不应该使渲染异步并将其保存在其他位置。

答案 1 :(得分:0)

如果您想在没有听众的情况下获得身高,可以使用以下方法:

const height = await StatusBarHeight.getAsync();