在React-Native中将数据从一个屏幕传递到另一个屏幕

时间:2020-09-22 13:24:30

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

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

lib2_test.cpp

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

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'
  }
});}

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


//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;

1 个答案:

答案 0 :(得分:0)

希望你做得更好 如我所见,您似乎希望在这一行将数据从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

希望会有所帮助