ReactJS 中的 Firebase 身份验证
Firebase authentication in ReactJS
我正在尝试使用 google 对用户进行身份验证。一切顺利。但是当我尝试在 onAuthStateChanged() 中 console.log(this) 打印类似
的内容时
Object { next: componentDidMount(user), error: noop(), complete: noop()
}
complete: function noop()
error: function noop()
next: function componentDidMount(user)
<prototype>: Object { … }
但是如果我 console.log(this) 在 onAuthStateChanged() 之外,它可以很好地处理当前 class.
的信息
我想要的是,我想使用此 this.setState() 方法使用用户详细信息更新状态信息。但是 this.setState() 方法在 onAuthStateChanged() 内部不起作用。
我该怎么做?
这是我的代码
componentDidMount = ()=>{
console.log(this)
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log(this)
console.log("userSignedIn")
} else {
console.log(" No user is signed in.");
}
});
};
问题在于 this
在回调中具有不同的含义,这取决于您声明它的方式。
最简单的解决方法是使用粗箭头来声明回调,就像您在其他地方所做的那样:
componentDidMount = ()=>{
console.log(this)
firebase.auth().onAuthStateChanged((user) => { //
if (user) {
console.log(this)
console.log("userSignedIn")
} else {
console.log(" No user is signed in.");
}
});
这是一个非常普遍的问题,因此我建议您在此处阅读更多相关内容:How to access the correct `this` inside a callback?
我正在尝试使用 google 对用户进行身份验证。一切顺利。但是当我尝试在 onAuthStateChanged() 中 console.log(this) 打印类似
的内容时Object { next: componentDidMount(user), error: noop(), complete: noop()
}
complete: function noop()
error: function noop()
next: function componentDidMount(user)
<prototype>: Object { … }
但是如果我 console.log(this) 在 onAuthStateChanged() 之外,它可以很好地处理当前 class.
的信息我想要的是,我想使用此 this.setState() 方法使用用户详细信息更新状态信息。但是 this.setState() 方法在 onAuthStateChanged() 内部不起作用。
我该怎么做?
这是我的代码
componentDidMount = ()=>{
console.log(this)
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log(this)
console.log("userSignedIn")
} else {
console.log(" No user is signed in.");
}
});
};
问题在于 this
在回调中具有不同的含义,这取决于您声明它的方式。
最简单的解决方法是使用粗箭头来声明回调,就像您在其他地方所做的那样:
componentDidMount = ()=>{
console.log(this)
firebase.auth().onAuthStateChanged((user) => { //
if (user) {
console.log(this)
console.log("userSignedIn")
} else {
console.log(" No user is signed in.");
}
});
这是一个非常普遍的问题,因此我建议您在此处阅读更多相关内容:How to access the correct `this` inside a callback?