【问题标题】:Passing Data from one screen to another in React-Native在 React-Native 中将数据从一个屏幕传递到另一个屏幕
【发布时间】:2020-09-22 13:24:30
【问题描述】:

这是我们从 API 获取数据的屏幕 1(LoginScreen.js) 代码,它在 JSON 格式,我们将在其中获取 'custRegId'、'email'、'firstName'、'lastName' 和 'mobileNumber'。

import {
  StyleSheet, TextInput, View, Text, ScrollView, Image, Keyboard, Button,
  TouchableOpacity, KeyboardAvoidingView, ActivityIndicator} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Loader from './Components/loader';
import axios from 'axios';
import HomeScreen from './drawerScreens/HomeScreen';

const LoginScreen = props => {
  let [userEmail, setUserEmail] = useState('');
  let [userPassword, setUserPassword] = useState('');
  let [loading, setLoading] = useState(false);
  let [errortext, setErrortext] = useState('');
  let [name, setName1] = useState('');
  let [item, setItem] = useState('');
  let [custRegId, setCustRegId] = useState('');

  const handleSubmitPress = () => {
    global.myUrl = 'Default API URL';
    setErrortext('');
    if (!userEmail) {
      alert('Please fill Email');
      return;
    }
    if (!userPassword) {
      alert('Please fill Password');
      return;
    }
    setLoading(true);
    var dataToSend = { email: userEmail, password: userPassword };
    var formBody = [];
    for (var key in dataToSend) {
      var encodedKey = encodeURIComponent(key);
      var encodedValue = encodeURIComponent(dataToSend[key]);
      formBody.push(encodedKey + '=' + encodedValue);
    }
    formBody = formBody.join('&');
    let data = {
      email: userEmail,
      password: userPassword
    }
    console.log(data.firstName)

    axios.post(myUrl, data, { withCredentials: true })
  .then(response => {console.log(response.data, "Logged in Successfully")
  .then((json) => {props.navigation.navigate('HomeScreen')})

      .catch(error => {
        setLoading(false);
        console.error("Incorrect Credentials");
      });
      console.log(setName1);
  });

  return (
    <View style={styles.mainBody}>
      <Loader loading={loading} />
      <ScrollView keyboardShouldPersistTaps="handled">
        <View style={{ marginTop: 100 }}>
          <KeyboardAvoidingView enabled>
            <View style={{ alignItems: 'center' }}>
              <Image
                source={require('../Image/aboutreact.png')}
                style={{
                  width: '90%',
                  height: 80,
                  resizeMode: 'contain',
                  margin: 30,
                }}
              />
            </View>
            <View style={styles.SectionStyle}>
              <TextInput
                style={styles.inputStyle}
                onChangeText={UserEmail => setUserEmail(UserEmail)}
                placeholder="Enter Email" 
                placeholderTextColor="#FFFFFF"
                autoCapitalize="none"
                keyboardType="email-address"
                ref={ref => {
                  this._emailinput = ref;
                }}
                returnKeyType="next"
                onSubmitEditing={() =>
                  this._passwordinput && this._passwordinput.focus()
                }
                blurOnSubmit={false}
              />
            </View>
            <View style={styles.SectionStyle}>
              <TextInput
                style={styles.inputStyle}
                onChangeText={UserPassword => setUserPassword(UserPassword)}
                placeholder="Enter Password" 
                placeholderTextColor="#FFFFFF"
                keyboardType="default"
                ref={ref => {
                  this._passwordinput = ref;
                }}
                onSubmitEditing={Keyboard.dismiss}
                blurOnSubmit={false}
                secureTextEntry={true}
              />
            </View>
            {errortext != '' ? (
              <Text style={styles.errorTextStyle}> {errortext} </Text>
            ) : null}
            <TouchableOpacity
              style={styles.buttonStyle}
              activeOpacity={0.5}>
              <Text style={styles.buttonTextStyle} 
              onPress={handleSubmitPress}>LOGIN</Text>
            </TouchableOpacity>
            <Text style={styles.registerTextStyle}>Don't have an account yet?</Text>
            <Text
              style={styles.registerTextStyle1}
              onPress={() => props.navigation.navigate('RegisterScreen')}>
               Register Here
            </Text>
          </KeyboardAvoidingView>
        </View>
      </ScrollView>
    </View>
  );
};
export default LoginScreen;

const styles = StyleSheet.create({
  mainBody: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#455a64',
  },
  SectionStyle: {
    flexDirection: 'row',
    height: 40,
    marginTop: 20,
    marginLeft: 35,
    marginRight: 35,
    margin: 10,
  },
  buttonStyle: {
    backgroundColor: '#5D6D7E',
    borderWidth: 0,
    color: '#FFFFFF',
    borderColor: '#7DE24E',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 20,
    marginBottom: 20,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
  inputStyle: {
    flex: 1,
    width:300,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    paddingLeft: 25,
    paddingRight: 15,
    borderWidth: 1,
    borderRadius: 30,
    borderColor: 'white',
    fontSize: 16
  },
  registerTextStyle: {
    color: '#FFFFFF',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 15,
  },
  errorTextStyle: {
    color: 'red',
    textAlign: 'center',
    fontSize: 14,
  },
  registerTextStyle1: {
    color: '#4493DC',
    textAlign: 'center',
    fontSize:14,
    fontWeight: 'bold'
  }
});}

这是屏幕 2(HomeScreen.js) 代码,我们需要从屏幕 1 获取数据,我们需要将“firstName”和“lastName”显示为“Welcome, Abdul Kalam!”。


//Import all required component
import { View, Text } from 'react-native';
import axios from 'axios';

const HomeScreen = (props) => {
  global.currentScreenIndex = 'HomeScreen';
  return (
    <View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
      <Text style={{ fontSize: 23, marginTop: 10 }}>Welcome, </Text>
    </View>
  );
};
export default HomeScreen;

**所以,请任何人帮助我如何将数据从 JSON 数据(如名字)传输到另一个屏幕 React-Native 的功能组件 所以输出应该是这样的: **

Welcome, Abdul Kalam!

【问题讨论】:

  • 感谢您的回复,我根据 react-native 文档尝试了但这没有帮助,它没有在第二个屏幕中显示数据
  • 您需要将数据从 Main 传递到 home,如 doc 在这行代码中的说明,props.navigation.navigate('HomeScreen',{data:json})

标签: reactjs react-native react-native-android react-navigation react-native-ios


【解决方案1】:

您似乎想在这一行将数据从 loginScreen 传递到 HomeScreen

.then((json) => {props.navigation.navigate('HomeScreen')})

好吧,我看到您正在检索数据并将其放入 json 变量中 因此,要将这些数据传递到 HomeScreen,您只需将这一行更改为

.then((json) => {props.navigation.navigate('HomeScreen', {json)}) // then you 
// send json variable to the HomeScreen like json:json

然后在 HomeScreen 文件中,您只需通过以下方式访问 json 变量

const data = navigation.route.params.json

【讨论】:

  • 感谢您的回复,但我收到错误消息:'TypeError: undefined is not an object (evalating 'navigation.route.params')' 并且来自 LoginScreen 我需要'firstName' (来自 JSON 文件)显示在 HomeScreen 中。那么请分享我的代码,好吗?
  • 你好亲爱的,是的,我好像错过了什么
  • 你好亲爱的,是的,我好像错过了什么。您必须更改屏幕const HomeScreen = ({navigation, route}) =&gt; { // your code} 的标记。然后你通过const data = route.params.json更改获取数据的位置,我认为这会起作用。干杯
  • 您好,谢谢您,我试过了,但抛出错误:'TypeError: undefined is not an object (evalating 'route.params')'
  • 下面是 HomeScreen 的代码,请更新代码没有任何错误: import React from 'react';从'react-native'导入{视图,文本};从'axios'导入axios; const HomeScreen = ({navigation, route}) => { global.currentScreenIndex = 'HomeScreen'; const data = route.params.json return ( 欢迎, );};导出默认 HomeScreen;
猜你喜欢
  • 1970-01-01
  • 2018-12-30
  • 2019-01-18
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多