React Native:在同级屏幕之间设置状态/传递数据

时间:2018-07-09 05:53:29

标签: react-native

我有一个名为“ Initial”的根组件,该组件负责渲染同级屏幕“ LoginScreen”和“ HomeScreen”(这是一个抽屉式导航器)。

在LoginScreen上,我正在执行验证并获得响应(例如(名称和图像))。我想通过LoginScreen中的此响应在抽屉导航器中设置名称和图像。

在不使用Redux的情况下实现此目标的最佳方法是什么? enter image description here

1 个答案:

答案 0 :(得分:0)

您始终可以通过导航参数传递数据。在此处阅读https://reactnavigation.org/docs/en/params.html

但是正确的解决方案是使用状态管理框架,例如redux或mobx。我建议使用mobx,因为它要简单得多。阅读此https://medium.com/react-native-training/react-native-with-mobx-getting-started-ba7e18d8ff44

但是有一种破解方法。您可以有一个单例对象,该对象会将这些信息保存在应用程序内存中,您可以在各个组件中使用它。

'Settings.js'

const Settings = {
  userName: "",
  avatar: "", // default avatar if you need

  getName() {
    return this.userName;
  },
  setName(userName) {
    this.userName = userName;
  },
  getAvatar() {
    return this.getAvatar;
  },
  setAvatar(avatarUrl) {
    this.avatar = avatarUrl;
  },

  initalizeData() {
    // make a http call to the server or
    // fetch it from local storage
    // and do
    // this.setName(name)
    // this.setAvatar(url)
  }
};

module.exports = Settings;

Init.js

export default class Init extends Component<Props> {

      componentWillMount(){
         //Settings.initalizeData() // if fetching from server or local storage 
         Settings.setName('John Doe')
      }


 }

App.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
const Settings = require("../Settings");


export default class App extends Component {

  componentDidMount(){
     console.log('Name',Settings.getName())
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}