2017-07-07 102 views
0

我想从另一个方法调用方法,我得到错误“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”不是一个函数。

我在做什么错,我该如何解决?

提前致谢!

回答

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. 
    } 
    } 
+0

谢谢!我在哪里可以了解更多关于这个箭头功能? –

+0

箭头功能是es6,你可以在这里阅读更多关于它的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions –

+0

非常感谢。 –