javascript - onAuthStateChanged 中的 React-native Firebase Auth setState 得到 TypeError: this.setState is not a function
问题描述
我从 react-native 开始,并尝试使用 onAuthStateChanged 获取 firebase 用户数据。
我试着去做bind
this
,但我仍然不知道。
这是我的构造函数
constructor(props) {
super(props);
this.state = {
isUid: '',
isProvider:'',
isPhoneNumber:'',
};
这是我在 componentDidMount 中的 onAuthStateChange
componentDidMount() {
var user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
user.providerData.forEach(function (profile) {
this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this);
this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
});
} else {
console.log('no user');
}
}
解决方案
由于您在onAuthStateChanged
回调中,this
因此与外部具有不同的含义。
最简单的解决方法是使用粗箭头表示法,它保持以下含义this
:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
user.providerData.forEach(function (profile) {
this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this);
this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
});
} else {
console.log('no user');
}
}
推荐阅读
- sql - 如何引用具有唯一约束的单列与另一列?
- r - 正则表达式和模式匹配来查找列表的元素,而不是字符串
- vba - Excel 2010 VBA 更新连接脚本停止工作
- javascript - 如何在不知道文件名的情况下指定下载文件夹?
- php - 如何在 PHP 的 Eclipse 内容辅助中禁用“无默认建议”?
- ionic3 - auth0/ionic3 本机应用程序运行时错误:无法解析存储的所有参数
- nginx - K8s Helm - Jenkins 与 Nginx Ingress
- statistics - 计算相对误差:哪个值是参考值?
- php - 如何在 Laravel Excel 3.0 中注册工作表(注册)事件
- optimization - 清零非规范化 - 它可靠吗?