无法访问 usefocusEffect 中 const 的更新状态

问题描述 投票:0回答:0

我是 React Native 的新手,我想访问 useFocusEffect 中变量的更新状态,目前在 start const [remember, setRemember] = useState() 中声明的 const 没有更新,我在 useFocusEffect 中使用它。关于这个的任何想法

  const rememberMe = ({ navigation }) => {
  const [remember, setRemember] = useState();

  useEffect(() => {
    getUserEmailAndPassword();
  }, []);

  const getUserEmailAndPassword = async () => {
    try {
      const loginSaved = await AsyncStorage.getItem("userLoginDetails");
      const currentUser = JSON.parse(loginSaved);
      if (currentUser?.state == true) {
        setRemember(true);
      } else {
        setRemember(false);
      }
    } catch (error) {}
  };

  useFocusEffect(
    useCallback(() => {
      return () => {
       // here remember is not updating 
        if (remember === true) {
          forgetUser();
        } else {
          try {
            const loginSaved = AsyncStorage.getItem("userLoginDetails");
            const currentUser = JSON.parse(loginSaved);
            if (
              currentUser?.userEmail !== null &&
              currentUser?.userPassword != null
            ) {
              rememberUser(
                currentUser?.userEmail,
                currentUser?.userPassword,
                (state = true)
              );
            }
          } catch (error) {}
        }
      };
    }, [])
  );

  const rememberUser = async (email, password, state) => {
    const userLoginDetails = {
      userEmail: email,
      userPassword: password,
      state: state,
    };
    try {
      await AsyncStorage.setItem(
        "userLoginDetails",
        JSON.stringify(userLoginDetails)
      );
    } catch (error) {
      // Error saving data
    }
  };

  const checkToRemember = (value) => {
    if (value == true) {
      setRemember(false);
    } else {
      setRemember(true);
    }
  };

  const forgetUser = async () => {
    try {
      await AsyncStorage.removeItem("userLoginDetails");
    } catch (error) {
      // Error removing
    }
  };

  return (
    <SafeAreaView
      style={styles.securityContainer}
      edges={["right", "top", "left"]}
    >
      <Toggle
        isOn={remember}
        onToggle={() => {
          setRemember(!remember);
          checkToRemember(remember);
        }}
      />
    </SafeAreaView>
  );
};

export default rememberMe;

当焦点被移除时,将记忆值设为未定义,它不会更新。

reactjs react-native react-hooks asyncstorage
© www.soinside.com 2019 - 2024. All rights reserved.