gpt4 book ai didi

javascript - React firebase auth() setState 在 then() 内不起作用

转载 作者:行者123 更新时间:2023-11-29 16:41:40 26 4
gpt4 key购买 nike

我从 firebase 文档登录了 Twitter,我想保存 uid 状态,但它不起作用。知道这里发生了什么吗?

twitterSignin(provider) {

var provider = new firebase.auth.TwitterAuthProvider();
var getStoreID = this.props.storeId;

firebase.auth().signInWithPopup(provider)
.then(function (result) {
var token = result.credential.accessToken;
var user = result.user;

var ref = firebase.database().ref(getStoreID);

ref.once("value")
.then(function (snapshot) {
var data = snapshot.val();

if (!data.owner) {
ref.set({
owner: result.user.uid
})
}

this.setState({
uid: result.user.uid
})

});
}).catch(function (error) {
console.log(error.code)
console.log(error.message)
});
}

谢谢

已修复:

    twitterSignin(provider) {

var provider = new firebase.auth.TwitterAuthProvider();
var getStoreID = this.props.storeId;
var that = this;

firebase.auth().signInWithPopup(provider)
.then(function (result) {
var token = result.credential.accessToken;
var user = result.user;

var ref = firebase.database().ref(getStoreID);

ref.once("value")
.then(function (snapshot) {
var data = snapshot.val();

if (!data.owner) {
ref.set({
owner: result.user.uid
})
}

that.setState({
uid: result.user.uid
})

});
}).catch(function (error) {
console.log(error.code)
console.log(error.message)
});
}

最佳答案

问题是您正在尝试从不同的范围访问setState。为了解决这个问题,您需要将回调绑定(bind)到实例。为此,您有几个选项,使用 bind,缓存父作用域 const me = this;,然后在回调中使用 me 或使用箭头函数。

twitterSignin(provider) {

var provider = new firebase.auth.TwitterAuthProvider();
var getStoreID = this.props.storeId;

firebase.auth().signInWithPopup(provider)
.then((result) => {
var token = result.credential.accessToken;
var user = result.user;

var ref = firebase.database().ref(getStoreID);

ref.once("value")
.then((snapshot) => {
var data = snapshot.val();

if (!data.owner) {
ref.set({
owner: result.user.uid
})
}

this.setState({
uid: result.user.uid
})

});
}).catch(function (error) {
console.log(error.code)
console.log(error.message)
});
}

我会选择箭头函数。


箭头函数在外部作用域中执行,在本例中是 twitterSignin 的作用域,它是您的 React 组件,带有 setState :)

关于javascript - React firebase auth() setState 在 then() 内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45154214/

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