如何将 async/await 与 useEffect React 挂钩一起使用,我尝试了很多示例但没有任何效果
How to use async/await with useEffect React hook, i tried a lot of examples and nothing is working
我需要使用 useEffect React 挂钩实现 async/await。我尝试了很多方法。每次报错:Hooks can only be called inside the body of a function component.
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 }
我会将它包装在一个匿名函数中并立即调用它:
我可能会试试这个:
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.
一切看起来不错,但也试试这个,
export const AuthLoadingScreen = ({ navigation }) => {...}
或
const AuthLoadingScreen = ({ navigation }) => {...}
export default AuthLoadingScreen;
我需要使用 useEffect React 挂钩实现 async/await。我尝试了很多方法。每次报错:Hooks can only be called inside the body of a function component.
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 }
我会将它包装在一个匿名函数中并立即调用它:
我可能会试试这个:
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.
一切看起来不错,但也试试这个,
export const AuthLoadingScreen = ({ navigation }) => {...}
或
const AuthLoadingScreen = ({ navigation }) => {...}
export default AuthLoadingScreen;