this.props.navigation 在我的 POST 方法中调用时失去价值
this.props.navigation loses value when called in my POST method
在我的注册页面中,我有一个被调用并注册用户的方法。但是,当我在注册用户后尝试导航回登录页面时,我得到 无法读取 属性 'navigation' of undefined。我的代码是
sendAjax = () => {
//this.props.navigation returns a value and I can navigate to 'Login'
if(!Regex.test(this.state.email)){
}else if(this.state.password != this.state.confirmPwd){
Alert.alert("The passwords don't match!");
}else{
const fn = encodeURIComponent(this.state.firstname);
...
const hashDigest = sha256(p);
const requestBody = `firstname=${fn}...
//POST
fetch("http://localhost:3000/users", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: requestBody
}).then(function (res, next) {
console.log("fetch request ", JSON.stringify(res.ok));
if(res.ok){
res.json().then(function (json) {
if(json.registerstate){
Alert.alert('Register success, please login');
//Cannot read property 'navigation' of undefined
this.props.navigation.navigate('Login')
}
});
}
})
.then((res) => {
Alert.alert("then working");
})
....
}
}
我不确定为什么 this.props.navigation.navigate 会在方法执行到一半时变成未定义的,但一开始我可以调用它。任何帮助都会很棒,谢谢!
此问题是"this"正在为您更改。使用箭头函数将 "outer this" 保持在范围内,而不是 "this" 因为在新函数中而改变。
在我的注册页面中,我有一个被调用并注册用户的方法。但是,当我在注册用户后尝试导航回登录页面时,我得到 无法读取 属性 'navigation' of undefined。我的代码是
sendAjax = () => {
//this.props.navigation returns a value and I can navigate to 'Login'
if(!Regex.test(this.state.email)){
}else if(this.state.password != this.state.confirmPwd){
Alert.alert("The passwords don't match!");
}else{
const fn = encodeURIComponent(this.state.firstname);
...
const hashDigest = sha256(p);
const requestBody = `firstname=${fn}...
//POST
fetch("http://localhost:3000/users", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: requestBody
}).then(function (res, next) {
console.log("fetch request ", JSON.stringify(res.ok));
if(res.ok){
res.json().then(function (json) {
if(json.registerstate){
Alert.alert('Register success, please login');
//Cannot read property 'navigation' of undefined
this.props.navigation.navigate('Login')
}
});
}
})
.then((res) => {
Alert.alert("then working");
})
....
}
}
我不确定为什么 this.props.navigation.navigate 会在方法执行到一半时变成未定义的,但一开始我可以调用它。任何帮助都会很棒,谢谢!
此问题是"this"正在为您更改。使用箭头函数将 "outer this" 保持在范围内,而不是 "this" 因为在新函数中而改变。