2017-07-07 98 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

非常感謝。 –