如何通过useEffect React钩子使用async / await,我尝试了很多示例,但没有任何效果

时间:2019-07-10 17:19:04

标签: reactjs async-await react-hooks

我需要使用useEffect React钩子实现async / await。我尝试了很多方法。每次出现错误时:只能在函数组件的主体内部调用挂钩。

import React, { useEffect } from 'react'
import { ActivityIndicator, StatusBar, StyleSheet, View } from 'react-native'
import * as Keychain from 'react-native-keychain'
import useEffectAsync from '../utils'

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center'
  }
})

const AuthLoadingScreen = ({ navigation }) => {
  useEffect(() => {
    const fetchData = async () => {
      const data = await Keychain.getGenericPassword()
      console.log('data', data)
      navigation.navigate(data ? 'App' : 'Auth')
    }
    fetchData()
  }, [])

  const { container } = styles
  return (
    <View style={container}>
      <ActivityIndicator />
      <StatusBar barStyle="default" />
    </View>
  )
}

export { AuthLoadingScreen }

2 个答案:

答案 0 :(得分:0)

我会将其包装在一个匿名函数中,并立即调用它:

我可以尝试:

const AuthLoadingScreen = ({ navigation }) => {
  useEffect(() => {
   (async () => {
      const data = await Keychain.getGenericPassword()
      console.log('data', data)
      navigation.navigate(data ? 'App' : 'Auth')
    })()

  }, [])

  const { container } = styles
  return (
    <View style={container}>
      <ActivityIndicator />
      <StatusBar barStyle="default" />
    </View>
  )
}

如果有效,请让我知道,因为我也在学习React Hooks:D。

答案 1 :(得分:0)

一切看起来不错,但也可以尝试一下

export const AuthLoadingScreen = ({ navigation }) => {...}

const AuthLoadingScreen = ({ navigation }) => {...}

export default AuthLoadingScreen;