неопределенный не является объектом (оценка ‘_ref.navigation’) Ошибка навигации React-native

#javascript #react-native #react-navigation

Вопрос:

Как устранить эту ошибку в навигации react Я не могу перемещаться по другому экрану с помощью функции passReg() ,

проверьте ниже мой полный код в моем ответе

Это моя ошибка

Ответ №1:

ЭТО МОЙ КОД, ПОЖАЛУЙСТА, РЕШИТЕ ЭТУ ОШИБКУ

 import 'react-native-gesture-handler';
import React,{ useState } from 'react';
import { StyleSheet, Text, SafeAreaView, ScrollView , View,Image,FlatList,RefreshControl,AsyncStorage,TextInput} from 'react-native';
import { TouchableRipple,Button} from 'react-native-paper';

import { useNavigation,NavigationContainer} from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import firebase from 'firebase';
import auth from '@react-native-firebase/auth';

import Reg from './Reg';

const Stack = createStackNavigator();

function passReg({ navigation })
  {
    navigation.navigate('reg');
  }


const PhoneSignIn=()=> {
  // If null, no SMS has been sent
  const [number, setNumber] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [code, setCode] = useState('');
  const [flag, setFlag] = useState();
  // Handle the button press
  async function signInWithPhoneNumber(phoneNumber) {
    const addNum = ' 91' phoneNumber;
    try{
      const confirmation = await auth().signInWithPhoneNumber(addNum);
      setConfirm(confirmation);
      } catch (error) {
        alert(error);
      }
  }

  async function confirmCode() {

    try {
      await confirm.confirm(code);

        if (confirm.confirm(code)) {  
          AsyncStorage.setItem('mo_num',number);
          alert("Congraulation....")
          datasend();
        }
    } catch (error) {
      alert(error);
    }
  }

  async function datasend()
  {

    fetch('https://punjabfoodhub.in/app/reg.php', {
          method: 'POST',
          mode: 'no-cors',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            'phone_num': number,
          })
        }).then((response) => response.json())
        .then((json) => {

          setFlag(json.flag);

          if (flag == 'reg') { passReg()}

        }).catch((err) => { console.log(err); });
  }

  
  if (!confirm) {
    return (
    
        <>
        <Image
          source={require('../assets/cover.png')}
          style={styles.image}
        />
        <View style={{padding:18}}> 
        <TextInput
          style={styles.input}
          placeholder=" 91 **********"
          onChangeText={num => setNumber(num)}
          keyboardType="numeric"
          autoCompleteType="tel"
          dataDetectorTypes="phoneNumber"

              />
          <Button icon="phone" mode="contained" style={styles.btn} onPress={() => passReg()}>
              SEND OTP
          </Button>
          </View>
        </>
    );
  }

  return (
    <>
      <Image
          source={require('../assets/cover.png')}
          style={styles.image}
        />
        <View style={{padding:18}}> 
      <TextInput
          style={styles.input}
          maxLength = {6}
          onChangeText={text => setCode(text)}
          keyboardType="numeric"
          placeholder="OTP"
      />
      <Button icon="camera" mode="contained" style={styles.btn} onPress={()=> confirmCode()}>
          Next
      </Button>
      <Button mode="text" color="gold" onPress={() => console.log('Pressed')}>
        Resend OTP ?
      </Button>
      </View>
    </>
  );
}


export default class Login extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
      number:null,
      otpsend:false,
      confirm:null,
      otp:null,
   };
  }

  render(){

    return(
      <ScrollView style={{backgroundColor:'#fff'}}>
         
        <PhoneSignIn/>
             <Stack.Navigator headerMode="none">
                <Stack.Screen name="main" component={PhoneSignIn} />
                <Stack.Screen name="reg" component={Reg} />
            </Stack.Navigator>   
      </ScrollView>
      )
  }
}

const styles = StyleSheet.create({
   container: {
    flex: 1,
    backgroundColor: '#FBFCFC', //#FFFAFA
    paddingHorizontal:12,
    //marginTop: Constants.statusBarHeight,
  },

  image:{
    width:'100%',
    height:250
  },


  input:{
      borderRadius:20,
       borderWidth: 2,
       borderColor:'gold',
       paddingHorizontal:20,
       fontSize:18
,  },

  btn:{
    borderRadius:20,
    backgroundColor:'gold',
     paddingVertical:5,
     marginTop:8
  }

 
});