我正在构建一个 react native 应用程序,但我似乎对useFocusEffect有问题? 当用户打开应用程序时,它会显示一个弹出窗口,提示他授予WRITE_SETTINGS_PERMISSION.一旦用户返回到应用程序屏幕,它应该判断权限是否成功授予,在这种情况下导航到新屏幕,否则继续显示弹出窗口.
import React, {useEffect, useState} from 'react';
import {View, Text, ActivityIndicator, Alert} from 'react-native';
import {useNavigation, useFocusEffect} from '@react-navigation/native';
import HotspotManager, {TetheringError} from '@react-native-tethering/hotspot';
const FirstScreen = () => {
const [loading, setLoading] = useState(true);
const [showPermissionsPopup, setShowPermissionsPopup] = useState(false);
const [permissionsGranted, setPermissionsGranted] = useState(false);
const navigation = useNavigation();
const requestWriteSettingsPermission = async () => {
try {
await HotspotManager.openWriteSettings();
const granted = await HotspotManager.isWriteSettingsGranted();
setPermissionsGranted(granted);
} catch (error) {
if (error instanceof TetheringError) {
console.log(error.message);
}
console.log(error);
}
};
const checkPermissions = async () => {
try {
const granted = await HotspotManager.isWriteSettingsGranted();
console.log(
`Write settings permission is ${granted ? 'granted' : 'not granted'}`,
);
setPermissionsGranted(granted);
} catch (error) {
if (error instanceof TetheringError) {
console.log(error.message);
}
console.log(error);
}
};
useFocusEffect(
React.useCallback(() => {
checkPermissions();
console.log('test1');
}, []),
);
useEffect(() => {
const timeout = setTimeout(() => {
setLoading(false);
setShowPermissionsPopup(true);
}, 2000);
return () => {
clearTimeout(timeout);
};
}, []);
useEffect(() => {
if (permissionsGranted) {
console.log('test2');
navigation.navigate('Network');
}
}, [navigation, permissionsGranted]);
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
{loading ? (
<ActivityIndicator size="large" color="blue" />
) : (
<Text>Welcome to My App!</Text>
)}
{showPermissionsPopup && !permissionsGranted && (
<View
style={{
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{backgroundColor: 'white', padding: 20}}>
<Text>Please grant the required permissions to continue.</Text>
<Text
style={{color: 'blue', textDecorationLine: 'underline'}}
onPress={requestWriteSettingsPermission}>
Grant Permissions
</Text>
</View>
</View>
)}
</View>
);
};
export default FirstScreen;
它运行得很好,除了当我从设置导航回到应用程序时,我必须再次按下"授予所需的权限",导航到设置,返回应用程序,然后它似乎才能工作,在这一点上,我被重定向到新屏幕. 我遗漏了什么?
我所能想到的就是,当用户返回到应用程序时,不会调用判断权限函数,因为在这种情况下不会触发焦点效果挂钩,但即使在这种情况下,我也无法使其工作.
我确实在主题中发现了一个类似的错误,但它似乎没有解决的办法,因为问题的创建者自己解决了它.