【问题标题】:How to pass parameter while navigating to previous screen?导航到上一个屏幕时如何传递参数?
【发布时间】:2017-10-21 21:21:39
【问题描述】:

我正在从屏幕 A 导航到屏幕 B.. 然后使用导航回到屏幕 A

this.props.navigation.goBack(null);

我想知道如何在执行此操作时传递参数?

这是我的代码

 import React, { Component } from 'react';
 import { View, Text, TextInput, ScrollView } from 'react-native';
 import Card from './Card';
 import CardSection from './CardSection';
 import MyButton from './MyButton';


 class Settings extends Component{
 constructor(props){
 super(props);
 this.state = {
   ip:'',
   port:''
 };
}

onSaveClick() {
 console.log('Button clicked');
 this.props.navigation.goBack();
}
render(){
const { input, container } = styles;
return(
  <View style = {container}>
  <Card>
  <CardSection>
    <TextInput 
      style = {input}
      onChangeText = {(ip) => this.setState({ip})}
      placeholder = "IP Address"
      autoCapitalize = "none"
      autoCorrect = {false}
      keyboardType = "numeric"
    />
    </CardSection>
    <CardSection>
      <TextInput
      style={styles.input}
      onChangeText={(port) => this.setState({port})}
      placeholder="Port Number"
      autoCapitalize="none"
      autoCorrect={false}
      keyboardType = "numeric"
    />
    </CardSection>
    <CardSection>
      <MyButton onPress ={this.onSaveClick.bind(this)}>
        Save
      </MyButton>
    </CardSection>
    <View>
    </View>
   </Card> 
  </View>
);
}
}

那么我怎样才能在前一个组件中访问该组件的状态。我们可以将状态作为参数传递吗?

【问题讨论】:

    标签: javascript react-native react-router react-navigation


    【解决方案1】:

    你应该遵循 Redux 方法

    因为将状态/信息从子组件传递回父组件(第二个屏幕到第一个屏幕)是一种糟糕的设计模式,因为这会在应用程序中创建多个数据流路径,从而难以调试。

    redux 如何提供帮助是

    1. 点击提交时,您将数据推送到全局存储中。(基本上调度一个动作并使用reducer更新全局redux存储)

    2. 导航回上一个屏幕。

    3. 通过 connect(来自 react -redux 包)在上一页列出这些更改并反映这些更改。

    可以使用 node 包 react-redux 。

    然后从这里跟进示例 -> http://redux.js.org/docs/basics/ExampleTodoList.html

    更多有用的例子here

    【讨论】:

    • 谢谢。为详细解释。我当然期待遵循这种设计模式。
    • 但就目前而言,我的应用只有两个屏幕。所以我想出了一个不用 Redux 的方法。我正在传递一个回调来更新状态作为导航参数到第二个屏幕。并通过它更新前一个组件的状态。由于我的应用只有两个屏幕,我认为这还可以。
    • 在很多情况下,打开一个屏幕并将数据传回前一个屏幕的模式并不是一个糟糕的设计模式,尤其是当您将其与使用一些全局数据存储将状态传回(为此,有一百万种方法可以做到这一点)。我非常希望看到一种导航结果的方法。无论如何,这个答案似乎只是 redux 的插件/广告,而不是提供除了“使用一些全局存储黑客”之外的直接答案,这本身就是对此类问题的明显答案。
    • 更容易使用上下文reactjs.org/docs/context.html,为什么不使用 AsyncStorage 来解决这样的小问题呢?我相信你在深入了解了 Redux 的优点之后才开始使用 Redux,而不仅仅是因为你想在屏幕之间保留一些信息。例如,如果我需要一个全局存储状态,我会开始使用 Redux,而不仅仅是因为我想在 2 个不同的屏幕之间使用相同的状态。
    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 2020-06-14
    • 2010-11-09
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多