我正在构建一个 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;

它运行得很好,除了当我从设置导航回到应用程序时,我必须再次按下"授予所需的权限",导航到设置,返回应用程序,然后它似乎才能工作,在这一点上,我被重定向到新屏幕. 我遗漏了什么?

我所能想到的就是,当用户返回到应用程序时,不会调用判断权限函数,因为在这种情况下不会触发焦点效果挂钩,但即使在这种情况下,我也无法使其工作.

我确实在主题中发现了一个类似的错误,但它似乎没有解决的办法,因为问题的创建者自己解决了它.

推荐答案

我所能想到的就是,当用户返回到应用程序时,不会调用判断权限函数,因为在这种情况下不会触发焦点效果挂钩,但即使在这种情况下,我也无法使其工作.

你说得对,你需要用AppState https://github.com/react-native-community/hooks#useappstate

// imports
import {useAppState} from '@react-native-community/hooks'


// start of the component
const currentAppState = useAppState()


// new code
useEffect(() => {
  if (currentAppState === 'active') {
    checkPermissions();
  }
}, [currentAppState]);

React-native相关问答推荐

类似Snapchat的Reaction Native筛选器

使用 Auth Token 标头react 本机图像,如何处理 401?

如何在react native 中将选定的自定义复选框数据发送到下一页?

React Native Navigation const { navigate } = this.props.navigation;

需要以前的props和state回调的静态 getDerivedStateFromProps?

如何在 react native 中以 redux 形式设置隐藏字段?

React-Native:无法从我的 android 应用程序打开设备设置

Eslint 错误,configuration for rule "import/no-cycle" is invalid

如何通过 node ID 获取真实元素?

TouchableOpacity 作为 ListView 中的 Item 仅在 TextInput 失go 焦点后做出响应

如何在获取请求中传递 POST 参数?

React-Native iOS - 如何通过按下按钮从 React-Native 视图导航到非 React-Native 视图(本机 iOS 视图控制器)?

React native base headers for ios not found

React native - 创建单例模式的最佳方式

使用 expo SDK react-native ios 应用程序的 Info.plist 文件

在 React Native 中,如何使用浅渲染测试我的组件?

如何在 react native 中将数组保存在异步存储中?

如何为 TouchableOpacity 组件创建禁用样式?

react-native图像预取

为什么我收到警告:函数作为 React 子级无效?