我需要用useEffect React hook实现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 }
一切看起来都不错,但也试试这个,
export const AuthLoadingScreen = ({ navigation }) => {...}
或
const AuthLoadingScreen = ({ navigation }) => {...}
export default AuthLoadingScreen;
我会把它包装在一个匿名函数中并立即调用它:
我可能会尝试这个:
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。