javascript - 我承诺正确链接吗?
问题描述
onSubmit(e) {
e.preventDefault();
const user = {
fname: this.state.firstname,
lname: this.state.lastname,
email: this.state.email,
username: this.state.username,
password: this.state.password
}
new Promise((resolve,reject) => {
this.props.fetchUser(this.state.username)
.then(res => {
this.setState({failed: this.props.exists})
if(!this.state.failed)
this.props.registerUser(user)
})
.then(res => {
this.setState({registered: this.props.status});
resolve();
})
})
}
这是我尝试链接承诺。这个想法是注册应该正确更新到 this.props.status 的状态(真/假)。
在第一个 Promise 中调用 this.props.registerUser 时,它会将 this.props.status 更改为 true。但是,registered 被设置为 false(这是调用 registerUser 之前 this.props.status 的值),而不是 true。
我确定 this.props.status 正在更改为 true,但已注册的状态没有更改。
我对这个东西很陌生。
解决方案
我假设fetchUser
andregisterUser
是返回承诺的函数。在这种情况下,您不需要将调用包装fetchUser
在 a 中,new Promise(...)
因为它会在调用时返回一个 Promise。
第二个then(...)
没有被调用的原因是你永远不会从第一个返回承诺then(...)
。
if(!this.state.failed)
this.props.registerUser(user)
应该成为
if(!this.state.failed)
return this.props.registerUser(user)
通过这两个修改,您的代码应该如下所示
this.props.fetchUser(this.state.username)
.then(res => {
this.setState({
failed: this.props.exists
});
if (!this.state.failed) {
return this.props.registerUser(user)
}
})
.then(res => {
this.setState({
registered: this.props.status
});
})
此外,您可能希望读取对象而不是组件道具fetchUser(...)
的结果。res
您应该注意的最后一个警告是,设置状态并在之后立即读取它并不能保证总是按预期工作。安全的方法是传递一个函数作为你的第二个参数,setState
当 React 更新状态时将调用该函数。
在这种情况下,最简单的方法是完全避免读取状态,而是使用临时变量。
const exists = this.props.exists;
this.setState({
failed: exists
});
if (!exists ) {
return this.props.registerUser(user)
}
推荐阅读
- python - 如何编写代码来识别发生移位的索引并从python中的另一个数组中获取相应的值?
- canvas - 在鼠标拖动时调整矩形大小的正确算法
- python - 将时间戳舍入到微秒 - 熊猫
- android - 如何从 Android 上不可绘制的图像中选择主色
- javascript - (节点:2256)UnhandledPromiseRejectionWarning:未处理的承诺拒绝
- sql - 如何限制选择与选择
- angular - Angular - 如何在 Angular 9 - Ivy 中进行代码拆分?
- python - 有没有办法让 for 循环在同一行打印下划线而不是在彼此下方?
- android - AWS Amplify Modlegen 生成 Android Studio 编译错误
- python - cv2.VideoCapture 冻结了我的整个计算机