【发布时间】:2019-03-04 21:36:39
【问题描述】:
我正在应用中进行身份验证,但我有点卡住了。我有 2 种不同的导航。一个显示用户是否已登录,另一个显示未登录。基本上,一个登录屏幕。如果我在开始时手动更改值,它工作正常。但是,例如,当用户登录时,我找不到改变状态的方法。即使 auth 模块中的值发生了变化,它也不会在 App.js 中更新 那么如何从登录屏幕更新 App.js 的状态?
import React, { Component } from 'react';
import { AppRegistry, Platform, StyleSheet, Text, View } from 'react-native';
import DrawerNavigator from './components/DrawerNavigator'
import SignedOutNavigator from './components/SignedOutNavigator'
import auth from './auth'
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super(props)
this.state = {
isLoggedIn: auth.isLoggedIn
}
}
render() {
return (
(this.state.isLoggedIn) ? <DrawerNavigator /> : <SignedOutNavigator />
);
}
}
AppRegistry.registerComponent('App', () => App)
还有我的认证模块,非常简单 从'react-native'导入{ AsyncStorage }; // 尝试从本地文件中读取 让 api_key 让 isLoggedIn = false
function save_user_settings(settings) {
AsyncStorage.mergeItem('user', JSON.stringify(settings), () => {
AsyncStorage.getItem('user', (err, result) => {
isLoggedIn = result.isLoggedIn
api_key = result.api_key
});
isLoggedIn = true
});
}
module.exports.save_user_settings = save_user_settings
module.exports.api_key = api_key
module.exports.isLoggedIn = isLoggedIn
【问题讨论】:
-
使用 redux 怎么样?我没有很多使用 React Native 的经验,但这是我会使用的方法
-
redux 对于这个问题来说是巨大的矫枉过正,重要的是要知道如何通过反应来做到这一点。你需要创建一个修改状态的函数,然后通过 props 将该函数传递给任何应该触发状态更改的组件
-
你能告诉我们你的身份验证模块吗?
-
azium 是对的。我知道我可以用 Redux 解决它,但这是一个我还没有准备好的大变化。因为我需要先正确学习 React
-
我在问题中添加了 auth.js。我想我明白你的意思,但我还不明白该怎么做。
标签: react-native authentication state react-navigation