首页 > 解决方案 > 使用反应钩子时屏幕不会更新,除非我重新加载应用程序

问题描述

我正在尝试使用电子邮件和密码登录我的用户。如果用户正确输入了他的凭据,我使用 AsyncStorage 将身份验证状态更新为“true”。

在我的主 App.js 文件中,我检查了 AsyncStorage,以查看身份验证状态是“真”还是假。问题是当用户登录并且 AsyncStorage 更新时,屏幕不会更新,除非我刷新应用程序(使用 fastreload)。

我本质上需要的是一种在 App.js 中重新渲染或重新运行代码的方法,而无需用户关闭应用程序然后重新打开它。

这就是我正在做的

export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  AsyncStorage.getItem("auth").then((val) =>
    val == "true" ? setIsAuthenticated(true) : setIsAuthenticated(false)
  );

  return isAuthenticated ? (
    <NavigationContainer>
      <Stack.Navigator headerMode="none" initialRouteName="Home">
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Orders" component={Orders} />
      </Stack.Navigator>
    </NavigationContainer>
  ) : (
    <NavigationContainer>
      <Stack.Navigator headerMode="none">
        <Stack.Screen name="Welcome" component={Welcome} />
        <Stack.Screen name="Login" component={Login} />
        <Stack.Screen name="Signup" component={Signup} />
      </Stack.Navigator>
    </NavigationContainer>
  );

}

我应该怎么做,以便我的应用程序在“auth”更改为“true”时立即重定向用户

标签: reactjsreact-nativereact-navigation

解决方案


尝试在 useEffect 挂钩中使用 AsyncStorage

useEffect(() => {
  AsyncStorage.getItem("auth").then((val) =>
  val == "true" ? setIsAuthenticated(true) : setIsAuthenticated(false)
);
}, []);

推荐阅读