我试图从另一个方法调用一个方法,我得到了错误" writeUserData"没有定义。 这是我的代码:
export default class RegisterScreen extends Component{
constructor(props){
super(props)
this.state = {
email: '',
password: '',
verify: '',
nickname: '',
}
this.handlePress = this.handlePress.bind(this)
this.writeUserData = this.writeUserData.bind(this)
}
handlePress(navigation){
if(this.state.password == this.state.verify){
firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(newUser){
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Home'})
]
})
navigation.dispatch(resetAction)
writeUserData(newUser.uid, this.nickname); //Problem here.
}).catch(function(error){
console.log(error);
});
}else{
//password not match, show error.
}
}
writeUserData(mUID, mNickname){
console.log("WRITE");
firebaseRef.database().ref('users/' + mUID + '/').set({
nickname: mNickname,
});
}
}
我尝试在注册到数据库后编写用户的昵称和UID。 我使用的是Firebase和React Native。
我也试过写这个.writeUserData,但是我得到一个错误说" this.writeUserData"不是一个功能。
我做错了什么,我该如何解决?
提前致谢!
答案 0 :(得分:2)
如果你使用箭头功能,它会将this
的引用更改为你的类,这将让你使用你的方法:
handlePress = (navigation) => { //this also makes it so you dont have to bind in constructor
if(this.state.password == this.state.verify){
firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((newUser) => { //arrow function here
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Home'})
]
})
navigation.dispatch(resetAction)
this.writeUserData(newUser.uid, this.nickname); //Problem here.
}).catch(function(error){
console.log(error);
});
}else{
//password not match, show error.
}
}