react-native - 从另一个组件更改 React Native App.js 中的状态

标签 react-native authentication state react-navigation

我正在应用程序中进行身份验证,但我有点卡住了。我有 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)

还有我的 auth 模块,非常简单 从'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

最佳答案

首先,有很多方法可以解决这个问题。因此,我将尝试向您解释为什么您现在所拥有的不起作用。

发生这种情况的原因是,当您将 auth.isLoggedIn 分配给 isLoggedIn 状态时,您将分配一次,有点作为副本。它不是存储的引用。

除此之外,请记住,React 状态通常仅使用 setState() 进行更新,并且这里永远不会调用它,因此您的状态不会更新。

我在不引入像 Redux 这样的元素的情况下解决这个问题的方法是考虑构建一个身份验证高阶组件来处理所有身份验证逻辑并包装整个应用程序,而 Redux 本身对于这个问题来说就太过分了。从那里您可以控制是否应该渲染子项,或者进行重定向。

身份验证组件

componentDidMount() {
 this._saveUserSettings(settings);
}

_saveUserSettings(settings) {
    AsyncStorage.mergeItem('user', JSON.stringify(settings), () => {
        AsyncStorage.getItem('user', (err, result) => {
            isLoggedIn = result.isLoggedIn
            api_key = result.api_key
        });
        this.setState({isLoggedIn: true});
    });
}

render() {
 const { isLoggedIn } = this.state;
 return isLoggedIn ? this.props.children : null;
}

App.js

render() {
   <AuthComponent>
      //the rest of authenticated app goes here
   </AuthComponent>
}

这是一个非常快速、不完整的示例。但它应该向您展示您可能希望如何进行身份验证。不过,您还需要考虑错误处理等。

关于react-native - 从另一个组件更改 React Native App.js 中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54991910/

相关文章:

Java - 通过用户身份验证访问文件

android - 在 Windows 中,react-native 启动命令永远无法执行

javascript - 如何从图书馆访问 redux store?

asp.net-mvc - 使用 MVC 5 Google AuthenticationOptions 在身份验证过程中获取额外的用户个人资料信息

php - 修改 Laravel 中的用户表

kotlin - 如何在函数式编程中处理私有(private)状态?

javascript - 如何使用正确的 isLoading 属性创建默认的 Vuex 状态

reactjs - 如何在 Reactjs 中一次调用上传多个图像文件

reactjs - 自动预测在 iOS 13 中无法使用 textContentType 到 TextInput

iphone - UITableView 失去选中状态 iOS