gpt4 book ai didi

javascript - React 的 SetState 在 Firebase Auth 的 onAuthStateChanged 中导致 setState 未定义

转载 作者:行者123 更新时间:2023-11-30 09:17:47 26 4
gpt4 key购买 nike

//为什么这个问题不是 (How to access the correct `this` inside a callback?) 的重复:我的问题是一个特定于 react 的问题,访问者可能不会在心理上将上述链接中提出的问题与我正在努力解决的问题联系起来与。

我正在尝试存储 Firebase auth 的 onAuthStateChanged 函数返回的用户数据,并将该数据存储在状态中,以便在我的 React 应用程序中使用它。在我的应用程序中,我有以下监听器:

  componentDidMount() {

firebase.auth().onAuthStateChanged(function(user) {

var theUser;

if (user) {
console.log("user is logged in!");

theUser = user;

this.setState({
session: theUser
});
// User is signed in.
} else {
// No user is signed in.
console.log("user is not logged in!")
theUser = null;
}
}
}

但我收到错误“TypeError:this.setState 不是一个函数”。我尝试将“this”绑定(bind)到 componentDidMount 无济于事。

最佳答案

正如@Jason Byrne 所说,指定谁是“这个”似乎是一个问题,您可以按照他在回答中提到的方法进行操作。

另一种现代方法是使用 ES6 arrow functions因为它们在 lexical scope 中工作,所以 this 取决于它被写入的“where”(这是你的 class):

componentDidMount() {

firebase.auth().onAuthStateChanged(user => {

var theUser;

if (user) {
console.log("user is logged in!");

theUser = user;

this.setState({
session: theUser
});
// User is signed in.
} else {
// No user is signed in.
console.log("user is not logged in!")
theUser = null;
}
}
}

也可以在这里查看:How to access the correct `this` inside a callback?

关于javascript - React 的 SetState 在 Firebase Auth 的 onAuthStateChanged 中导致 setState 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53892261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com