我在学习redux在我的 react-native
android 应用程序中实现。我看到它有助于维护应用程序中的状态。
例如,如果用户已经登录,那么它有助于将用户状态保存到登录状态。我希望我举了正确的例子。我看到 react-native
也有 AsyncStorage
,无论用户是否登录,我们都可以在其中保存它。
如果用户已经登录,我们可以编写一个逻辑,然后在 AsyncStorage
中将登录设置为 true,在注销时将其设置为 false。现在,检查启动画面是真还是假,然后相应地导航。
如果可以使用 AsyncStorage
管理此状态,那么现在有点困惑,那么 react-native
中 redux
的用例是什么应用。谁能举个例子解释一下?
最佳答案
AsyncStorage
用于 react-native 就像 localStorage
用于浏览器一样,但它是异步的。
我假设您使用 JWT 进行身份验证,您可以使用 AsyncStorage
来存储 token 。
// on login
AsyncStorage.setItem('@token', value)
在应用程序的入口屏幕中,您可以从 AsyncStorage
获取 token ,并根据 token 的解码值更新存储并进行重定向。
// componentWillMount
AsyncStorage.getItem('@token')
.then(token => {
const decodedToken = decodeToken(token)
if (isExpired(decodeToken)) // redirect to login
// save the values to the store
someAction(decodedToken)
})
无论如何,如果你在你的应用程序中使用 redux,无论是什么框架,所有与你的应用程序状态相关的东西都应该由 redux 处理。
总而言之,您应该使用 AsyncStorage
来存储 token ,而不是像 isConnected, isLoggedIn, user
...
关于android - React Native 应用程序中的 Redux 用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016702/