reactjs - 使用反应钩子时屏幕不会更新,除非我重新加载应用程序
问题描述
我正在尝试使用电子邮件和密码登录我的用户。如果用户正确输入了他的凭据,我使用 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”时立即重定向用户
解决方案
尝试在 useEffect 挂钩中使用 AsyncStorage
useEffect(() => {
AsyncStorage.getItem("auth").then((val) =>
val == "true" ? setIsAuthenticated(true) : setIsAuthenticated(false)
);
}, []);
推荐阅读
- sql - 如何找到多列最小的行
- java - 如何编写一个显示仅分配给登录用户的列表的 SQL 查询?
- sql - SQL Developer:需要帮助确定列中的数据是否从负数变为正数,反之亦然
- java - ElasticSearch 6.8 Java 库:发送 UpdateRequest 时覆盖 Object 类型的字段而不是合并
- java - 查找重复的单词
- ios - Swift 5 - 如何在 iPad 上手动更改设备方向
- javascript - firebase.auth.onAuthStateChanged 也在令牌刷新时触发
- python - pip install 不会被本地依赖项的 --no-index 和 find-links 覆盖
- c - Xcode system("afplay music.wav"); 似乎不起作用
- android - 我无法从 Instagram api 解析 json