2017-08-07 26 views
-3

我有我的方法Reactjs:类型错误:this.authHandler不是一个函数

authHandler(authData){ 

    if(!this.isMounted()) 
     return; 

    const storeRef = myDatabase.ref(this.props.storeId); 

    storeRef.once('value', (snapshot) => { 
     const data = snapshot.val() || {}; 

     if(!data.owner){ 
      storeRef.set({ 
       owner: authData.user.uid 
      }); 
     } 

     this.setState({ 
      uid: authData.user.uid, 
      owner: data.owner || authData.user.uid 
     }); 

     // localStorage.setItem(`authData-${this.props.storeId}`, JSON.stringify(authData)); 
    }); 
} 

这里是componentDidMount()

componentDidMount(){ 

    app.auth().onAuthStateChanged(function(user, error){ 
     if(!error && this.handleErrors){ 
      this.handleErrors(error); 
      return; 
     } 

     if(user){ 
      console.log(user); 
      this.authHandler(user); 
     } 
    }); 
} 

但无论我做什么,它总是抛出:

TypeError: this.authHandler is not a function

我读了一堆类似的问题:例如 ReactJS - this.functionname is not a function

但他们都没有为我工作。

请帮忙。

+1

使用箭头功能的事件处理程序。 – Li357

+0

@AndrewLi谢谢,这对我有用,请你解释一下原因吧?谢谢 – Franva

+1

查看链接。 TLDR常规函数表达式通过调用它们的方式来设置它们的'this'。通常,'this'会在回调中的常规函数​​表达式中引用'window',因为它们是如何被调用的。箭头函数不会绑定他们自己的'this'。箭头函数内的'this'值是指来自封闭范围的'this'。因此,箭头函数内的'this'将引用组件,而不是'window'。 – Li357

回答

-1

只需使用箭头功能:

componentDidMount(){ 

    app.auth().onAuthStateChanged((user, error) => { 
     if(!error && this.handleErrors){ 
      this.handleErrors(error); 
      return; 
     } 

     if(user){ 
      console.log(user); 
      this.authHandler(user); 
     } 
    }); 
} 
+0

感谢亚历山大,它适用于我:)但你能解释一下原因吗?谢谢 – Franva

+1

箭头函数有“词法作用域”而不是“动态的”,所以你将把你的类作为“this”而不是其他类或函数。你可以在这里阅读https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/ –

+0

美丽,谢谢〜! – Franva

相关问题