React Native - Navigation.navigate()只在onPress函数中工作



在我的应用程序中

onPress={() => navigation.navigate('<ScreenName>')} 

工作完美,而如果我试图在点击按钮时调用的函数中更改屏幕,例如

const signup = (mobileNumber, {navigation}) => {
Object.keys(mobileNumber).forEach((key) => {
console.log(mobileNumber[key]);
});
if (mobileNumber.mobileNumber == null) {
Alert.alert("Oops!", "Please insert your mobile number.");
return;
}
let dataToSend = {mobile_number: mobileNumber.mobileNumber};
let formBody = [];
for (let key in dataToSend) {
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
fetch('https://mywebsite.com/api/v1/createAccount.php', {
method: 'POST',
body: formBody,
headers: {
//Header Defination
'Content-Type':
'application/x-www-form-urlencoded;charset=UTF-8',
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
//Alert.alert("Excellent!", "Please go on");
navigation.navigate('<ScreenName>');
} else {
console.log('Please check your mobileNumber');
}
})
.catch((error) => {
//Hide Loader
console.error(error);
});
}

function JoinScreen({ navigation }) {
const [mobileNumber, setMobileNumber] = useState(null);
const [isLoading, setLoading] = useState(true);
const [data, newData] = useState(null);
useEffect(() => {
fetch("https://mywebsite.com/api/v1/createAccount.php")
.then((response) => response.text())
.then((response) => newData(response));
}, []);
return (
<>
<StatusBar hidden />
<SafeAreaView style={{ flex: 1, alignItems: 'center', backgroundColor: '#262423' }}>
<TextInput
style={styles.input}
placeholder="Your mobile number"
placeholderTextColor="#fff"
autoCapitalize="none"
autoCorrect={false}
onChangeText={(val) => setMobileNumber(val)}
keyboardType="phone-pad"
/>
<TouchableOpacity onPress={() => signup({ mobileNumber })}>
<Text style={{ textAlign: "center", paddingTop: 20, color: "#babf26", fontSize: 20 }} >Create account</Text>
</TouchableOpacity>
</SafeAreaView>
</>
);

}

应用返回">TypeError: undefined不是一个对象(求值'_ref6.navigation')">

如果在"注册"函数不换行"navigation"在花括号内,我得到">undefined不是一个对象(求'navigation.navigate')">

没有将navigation对象传递给signup函数。该声明

const signup = (mobileNumber, {navigation})

无效。花括号用于解构传递给函数的对象的属性。JoinScreen({ navigation })工作的原因(很可能)是因为JoinScreen被定义为导航器内的屏幕。因此,导航框架将一个对象传递给导航器中定义为屏幕的所有屏幕,该对象的一部分是navigation对象,您可以使用花括号对其进行解构。

对于signup,情况并非如此,因为这只是一个函数。但是,您可以像下面这样从JoinScreen传递它。

function JoinScreen({ navigation }) {
...
<TouchableOpacity onPress={() => signup(mobileNumber, navigation)}>
<Text style={{ textAlign: "center", paddingTop: 20, color: "#babf26", fontSize: 20 }} >Create account</Text>
</TouchableOpacity>
}

然后,你的注册功能。

const signup = (mobileNumber, navigation) => {
...
}

你的注册函数应该在你的屏幕组件中,或者你应该传递导航对象作为参数。

最新更新