我需要使用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 }
答案 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;