挂钩调用无效。挂钩只能在函数组件的主体内部调用 - 尝试使用 useNavigation() 重定向时显示的错误
Invalid hook call. Hooks can only be called inside of the body of a function component - error displayed when tryingto use useNavigation() to redirect
我是 React native 的新手,我尝试在 Facebook 登录后重定向,但我得到了 Invalid hook call. Hooks can only be called inside of the body of a function component
。我这是我的代码。请给我一些帮助解决这个问题。登录一直有效,直到我尝试使用 useNavigation()。
export default function LoginScreen({ path }: { path: string }) {
return (
<Container style={styles.container} >
<FormControl>
<Button style={styles.loginButton} onPress={FacebookLogin}>
<Text style={styles.textButton}>Login with Facebook</Text>
</Button>
</FormControl>
</Container>
);
}
async function FacebookLogin(){
try {
await Facebook.initializeAsync({
appId: '...',
});
const data = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (data.type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${(data.token)}`);
//type authScreenProp = StackNavigationProp<RootStackParamList, 'Dashboard'>;
// const navigation = useNavigation<authScreenProp>();
//rconsole.log(await response.json());
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
const navigation = useNavigation();
navigation.navigate('Dashboard');
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
如错误所述,您不能在函数组件外部调用钩子,因此您需要将 const navigation = useNavigation();
移动到 LoginScreen
并将其作为参数传递给处理程序:onPress={()=>FacebookLogin(navigation )}
我是 React native 的新手,我尝试在 Facebook 登录后重定向,但我得到了 Invalid hook call. Hooks can only be called inside of the body of a function component
。我这是我的代码。请给我一些帮助解决这个问题。登录一直有效,直到我尝试使用 useNavigation()。
export default function LoginScreen({ path }: { path: string }) {
return (
<Container style={styles.container} >
<FormControl>
<Button style={styles.loginButton} onPress={FacebookLogin}>
<Text style={styles.textButton}>Login with Facebook</Text>
</Button>
</FormControl>
</Container>
);
}
async function FacebookLogin(){
try {
await Facebook.initializeAsync({
appId: '...',
});
const data = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (data.type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${(data.token)}`);
//type authScreenProp = StackNavigationProp<RootStackParamList, 'Dashboard'>;
// const navigation = useNavigation<authScreenProp>();
//rconsole.log(await response.json());
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
const navigation = useNavigation();
navigation.navigate('Dashboard');
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
如错误所述,您不能在函数组件外部调用钩子,因此您需要将 const navigation = useNavigation();
移动到 LoginScreen
并将其作为参数传递给处理程序:onPress={()=>FacebookLogin(navigation )}