React Native - Navigation.navigate() 仅在 onPress 函数中有效
2022-05-02
759
在我的应用中,
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’) ”
如果有帮助,如果在“signup”函数中我没有将“navigation”括在花括号内,我会得到“ undefined 不是对象(正在评估‘navigation.navigate’) ”
2个回答
您没有将
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) => {
...
}
David Scholz
2022-05-02
您的注册功能应该位于屏幕组件内部,或者您应该将导航对象作为参数传递。
Ian Hudicourt
2022-05-02