【问题标题】:Add data in React Native and Save the State在 React Native 中添加数据并保存状态
【发布时间】:2018-06-19 17:10:53
【问题描述】:

我正在构建一个基本的 React Native 应用程序,其中用户在 TextInput 中输入他的名字,然后按下按钮,他的名字连同他的图像一起被添加到另一个视图中的 ScrollView 中。图像根据人名进行存储和命名。示例 - 名称:'ABC',从资产中获取的图像将是 'ABC.jpg'。

我可以为一个人做这件事,但是每次我添加一个新条目时,前一个条目都会被覆盖。我怎样才能保留以前的条目并添加另一个条目?

首页

import React, {Component} from 'react';
import { StyleSheet, Text, View, Image, ScrollView, Button, TouchableWithoutFeedback, TextInput} from 'react-native';
import { createStackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
    render() {
        const { navigation } = this.props;
        const name0 = navigation.getParam('name0', 'NO-ID');
        return (
            <View style={styles.container}>
              <ScrollView vertical={true} contentContainerStyle={{flexGrow: 1}}>
              <Text style={styles.category}>Category 1</Text>


              <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
                  <TouchableWithoutFeedback onPress={() => {
                        this.props.navigation.navigate('Details', {
                        name: name0,
                        intro: 'lorem ipsum',
                        detail1: 'XYZ',
                        detail2: 'ABC',
                        });
                  }}>
                  <View style={styles.view}>
                      <Image source={require('./assets/rohit.jpg')} style={styles.image}></Image>
                      <Text style={styles.text}>{name0}</Text>
                  </View>
                  </TouchableWithoutFeedback>
                  </ScrollView>



              </ScrollView>
            </View>
        )
    }
}

添加数据

class AddData extends React.Component {
    constructor(props) {
    super(props);
    this.state = { text: '' };
}
  render() {
      function onPressLearnMore() {
          alert('Hi')
      }
    return (
      <View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
          <TextInput
          style={{height: 40,width:200}}
          onChangeText={(text) => this.setState({input: text})}
        />
        <Button
        onPress={() => {
              this.props.navigation.navigate('Home', {
              name0: this.state.input
              });
        }}
        title="Pass Data"
        />

      </View>
    );
  }
}

导航器

const RootStack = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
    Data: AddData
  },
  {
    initialRouteName: 'Data',
  }
);

export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

Screen 1 Screen 2

【问题讨论】:

  • 您可以使用 asyncstorage 在本地保存数据。

标签: reactjs react-native react-navigation


【解决方案1】:

因为您没有将用户输入的数据保存在任何地方,只是将其传递回主页,因此它会被覆盖,并且当您的代码存在时,它就可以工作了! ;)

简单地对你正在做的事情做一个创可贴,因为这种传递数据的方法有点禁忌......如果没有像 AsyncStorage 这样的状态持久性,你就无法实现你的要求,或者......有两个屏幕。因为每次 React 重新渲染你的屏幕时,你状态对象中的任何数据都会消失......

在您的 home 组件中,在 mount 时您可以将用户输入存储为数组中的对象。在下面的示例中,我使用的是您发送回家乡的用户数据,但是这需要是从某种持久性中检索到的数据。

class HomeScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
  usersArray: []
}
}
componentDidMount() {
  let userInfo = this.props.navigation.getParam('name0', 'NO-ID');
  userInfo !== undefined ? this.setState({usersArray: 
[...this.state.usersArray, userInfo]}) : console.log('NO USER DATA to add')
}
render() {
    const { navigation } = this.props;
    const name0 = navigation.getParam('name0', 'NO-ID');
    return (
        <View style={styles.container}>
          <ScrollView vertical={true} contentContainerStyle={{flexGrow: 1}}>
          <Text style={styles.category}>Category 1</Text>


          <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
              <TouchableWithoutFeedback onPress={() => {
                    this.props.navigation.navigate('Details', {
                    name: name0,
                    intro: 'lorem ipsum',
                    detail1: 'XYZ',
                    detail2: 'ABC',
                    });
              }}>
              <View style={styles.view}>
                  <Image source={require('./assets/rohit.jpg')} style={styles.image}></Image>
                  {/* <Text style={styles.text}>{name0}</Text> */}
                 { this.state.usersArray.map((ele, index) => {
                    return <Text key={index} style={styles.text}>{ele.name}</Text>

                  })}
              </View>
              </TouchableWithoutFeedback>
              </ScrollView>



          </ScrollView>
        </View>
    )
  }
}

请记住,您可能需要将您的用户数据更改为对象以供此休息和传播工作。

【讨论】:

    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多