如何将本地数据从一个屏幕发送到另一个屏幕?

时间:2017-09-28 18:52:16

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

我是新手反应原生如何使用Android中的道具将数据从一个屏幕发送到另一个屏幕而不是ios我的代码如下所示

Home.js

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      qwerty:{
        data:[],
      },
    };
  }

  goPressed(navigate){
     navigate("Product");
  }

  render() {
      const { navigate } = this.props.navigation;

      contents = this.state.qwerty.data.map((item) => {
        return (
            <View key={item.p1.id}>
            <View>
              <Text>{item.p1.content}</Text>
            </View>
            <View>

            <TouchableHighlight onPress={() => this.goPressed(navigate)}>
              <Text>
                Go
              </Text>
            </TouchableHighlight>

            </View>
          </View>
          );
       });

      return (
        <ScrollView style={styles.container}>
          {contents}
        </ScrollView>
      );
    }
  }

  export default Home;

这是我的home.js,我想传递数据,即{item.p1.content}到另一个屏幕,即product.js,那么我该怎么做呢?我应该做什么修改?

Product.js

      export default class Products extends Component {
  static navigationOptions = {
    title: "Products",
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Text>{item.p1.content}</Text>
      </View>
    );
  }
}

3 个答案:

答案 0 :(得分:1)

你的应用程序在成长,你需要redux来持久化状态并将数据从容器投射到子组件。

请阅读此内容。我在我的应用程序中使用它

https://github.com/reactjs/redux

http://redux.js.org/docs/api/Store.html

但我也使用redux-saga,这是更复杂的

答案 1 :(得分:1)

一种方法是简单地将您在'qwerty'中存储的日期作为道具传递给下一个场景。

在Home.js中,您可以将goPressed方法修改为......

  goPressed(navigate){
     navigate("Product", {passedData: this.state.qwerty.item.p1.content});
  }

然后在Product.js中,您需要将代码修改为

render() {
    return (
      <View style={{ flex: 1 }}>
        <Text>{this.props.passedData}</Text>
      </View>
    );
  }

答案 2 :(得分:0)

将数据发送到其他屏幕

this.props.navigation.navigate('Your Screen Name' , { YourParamsName: "Foo"});

从其他屏幕接收数据

this.props.navigation.state.params.YourParamsName