【问题标题】:Passing State to another Component in React Native在 React Native 中将状态传递给另一个组件
【发布时间】:2019-05-30 06:16:43
【问题描述】:

React Native 新手在这里。

我在这里有一个(在我看来)常见的用例。我使用 React Navigation 并有 4 个不同的选项卡。在第一个选项卡中,我有一个 FlatList,我想从中选择收藏夹。然后,这些收藏夹应列在另一个选项卡中。到目前为止没有更多内容。

我遇到的问题是我没有弄清楚如何将我在第一个选项卡的状态中声明的收藏夹变量传输到另一个选项卡。也许这种方法也完全错误..

第一个标签/屏幕

import React, {Component} from 'react';
import { FlatList, Text, View, ScrollView, Image, TouchableHighlight} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'

export default class HomeScreen extends Component {

  state = {
    data: [],
    favourites: []
  };

  //Function called on the click of the Heart Button, adding the List Element to the State
  addFav = item => {
    this.setState((prevState) => ({'favourites': prevState.favourites+item.title+' '}))
    alert(item.title)
  }

  componentWillMount() {
    this.fetchData();
  }

  //Fetching the data from the API
  fetchData = async () => {
    const response = await fetch("http://192.168.1.19:8080/v1/api/event");
    const json = await response.json();
    this.setState({ data: json});
  };

  render() {
    return <FlatList
          ItemSeparatorComponent={() =>
            <View
              style={{ height: 1, width: '100%', backgroundColor: 'lightgray' }}
            />
          }
          data={this.state.data}
          keyExtractor={(item => item.title)}
          renderItem={({ item }) =>
            <ScrollView>
              <Image style={{alignSelf:'stretch', width:undefined, height:undefined, flex : 1, borderRadius:10}} source = {require('../img/landscape.jpeg')}/>
              <TouchableHighlight onPress={()=>this.openEvent(item)}>
                <View style={{flex: 1, flexDirection:'row', padding: 5}}>
                  <View style={{flex: 1}}>
                    <Text style={{fontSize:15, textAlign:'center', padding: 2}}>{this.timeConverterMonth(item.time)}</Text>
                    <Text style={{fontSize:15, textAlign:'center', padding: 2}}>{this.timeConverterDay(item.time)}</Text>
                  </View>
                  <View style={{flex: 4}}>
                    <Text style={{fontSize:15, padding: 2}}>{item.title}</Text>
                    <Text style={{fontSize:10, padding: 2}}>{item.locShort}</Text>
                  </View>
//That's where the function is called
                  <TouchableHighlight 
                    style={{flex: 2}} 
                    onPress={() => this.addFav(item)}
                  >
                    <Icon name="ios-heart-empty" size={24} style={{alignSelf: 'center', padding: 10}}/>
                  </TouchableHighlight>
                </View>
              </TouchableHighlight>
//just checking the state
              <Text>{this.state.favourites}</Text>
            </ScrollView>}
        />;
  }
}

第二个标签/屏幕

import React, {Component} from 'react';
import {Text} from 'react-native';

export default class FavouritesScreen extends Component {

  constructor(props){
    super(props)
  }

  render(){
//Here I want to display my favourites Array from the HomeScreen State
    return <Text>{this.props.favourites}</Text>;
  }
}

我实际上并不想知道为什么它不起作用,我只是通过阅读所有其他文章尝试了 props 方法,但屏幕不在父/子关系中。

所以我想做的是在第二个标签中

HomeScreen.state.favourites

谢谢。

【问题讨论】:

    标签: react-native react-navigation react-component


    【解决方案1】:

    您的情况很常见。我面临的一个问题是在应用程序之间传递“共享状态”。

    组件具有本地状态,您可以通过道具(您已经提到)将其传递给子组件。

    当您想在另一个组件中访问该状态时,就会出现问题。这里的解决方案是拥有一个全局状态。

    您可能需要考虑将 Redux 用于您的应用程序。

    https://redux.js.org/introduction/getting-started

    来自 redux 网站:

    Redux 是 JavaScript 应用程序的可预测状态容器。

    它可以帮助您编写行为一致、运行在 不同的环境(客户端、服务器和本机),并且易于 测试。最重要的是,它提供了出色的开发人员体验,例如 作为实时代码编辑与时间旅行调试器相结合。

    基本上,您将获得一个全局状态,您的应用程序的所有组件都可以访问该状态。这允许您更新一个组件中的状态并在另一个组件中访问它们。

    我会警告你,这不是最容易学习的东西。当你第一次看到它时 - 它有点令人生畏。但是,随着您的应用程序变得越来越复杂并且您添加了更多状态 - 您会很高兴您使用它。

    好消息是,Redux 与 React 和 React Native 有很好的文档记录 - 所以你应该找到很多关于如何将它集成到你当前应用程序中的教程。

    【讨论】:

      【解决方案2】:

      拥有“全局”访问状态的用例是状态管理库的用例。一个很好的例子是 Redux 库 - 在这种情况下,您可以将收藏夹存储在一个名为“HomeScreen”的状态下,并将其映射并使用它在应用程序其余部分的任何屏幕中。

      这是一篇关于 redux 入门的好文章:https://blog.cloudboost.io/getting-started-with-react-native-and-redux-6cd4addeb29

      【讨论】:

        猜你喜欢
        • 2019-07-17
        • 1970-01-01
        • 2019-10-23
        • 2017-11-07
        • 2016-12-05
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多