我有我的方法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
但他们都没有为我工作。
请帮忙。
使用箭头功能的事件处理程序。 – Li357
@AndrewLi谢谢,这对我有用,请你解释一下原因吧?谢谢 – Franva
查看链接。 TLDR常规函数表达式通过调用它们的方式来设置它们的'this'。通常,'this'会在回调中的常规函数表达式中引用'window',因为它们是如何被调用的。箭头函数不会绑定他们自己的'this'。箭头函数内的'this'值是指来自封闭范围的'this'。因此,箭头函数内的'this'将引用组件,而不是'window'。 – Li357