javascript - 在 React.js 中使用异步回调函数时无法读取状态
问题描述
因此,我从 stackoverflow 的帖子中复制了此功能,我的目标是能够在注册后立即更新数据库和配置文件信息,然后再转到其他路线,结果与我预期的一样有效,但我无法再访问回调中的状态,请有人帮我调试这段代码:
signup = (e) => {
this.setState({ loading: true });
e.preventDefault();
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((userCredentials) => {
if (userCredentials.user) {
userCredentials.user.updateProfile({
displayName: this.state.username,
photoURL: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQdVmHPt9SajdsWlAZWzqRXkd-SzmmO9bBUV45fLnw5giijsty3OA',
}).then((s) => {
fire.database()
.ref(`master/${userCredentials.user.displayName}/setup/`)
.update({
bio: 'Be original',
})
.then(() => {
window.location.reload();
});
})
}
})
.catch(function (error) {
console.log(error);
this.setState({ signupError: true, loading: false, });
});
}
错误发生在 catch(error)
TypeError:无法读取未定义的属性“setState”
我怀疑问题来自使用多个.then
解决方案
this
incatch
不是您的班级,请查看普通功能和箭头功能之间的区别。有两种方法可以解决您的问题。
- 第一:使用箭头函数
.catch(function (error) {
console.log(error);
this.setState({ signupError: true, loading: false, });
});
- 第二:设置局部
self
变量为this
signup = (e) => {
this.setState({ loading: true });
e.preventDefault();
const self = this; // It can be what ever you want, `self` is the most popular
...
}
然后
.catch(function (error) {
console.log(error);
self.setState({ signupError: true, loading: false, });
});
推荐阅读
- ajax - AJAX 函数总是返回 html 代码以响应成功
- ios - ScrollView 水平和垂直移动..Frame 问题
- angular - 资产目录中的 Angular 7 静态配置文件
- c++ - 是否可以声明一个 constexpr 指针而不是指向 constexpr 的指针?
- sql-server - 如何获得前几个月的名字
- javascript - 有什么功能可以读取(excel文件)中的多张纸吗?
- python-imaging-library - python枕头增加gif文件大小x10
- reactjs - 身份验证完成前受保护的路由重定向
- jmeter-5.0 - 如果我们通过 HTTPS 代理服务器记录脚本,我们如何在 jmeter 中获取记录日志?
- django - 根据周数注释查询的响应