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();
})
})
}
这是我对链接 promise 的尝试。这个想法是 registered 应该正确更新到 this.props.status (true/false) 的状态。
当在第一个 promise 中调用 this.props.registerUser 时,它会将 this.props.status 更改为 true。但是,registered 被设置为 false(这是调用 registerUser 之前 this.props.status 的值),而不是 true。
我确定 this.props.status 正在变为 true,但 registered 状态没有改变。
我是新手。
最佳答案
我假设 fetchUser
和 registerUser
是返回 promise 的函数。在这种情况下,您不需要将对 fetchUser
的调用包装在 new Promise(...)
中,因为它会在调用时返回一个 promise。
第二个 then(...)
没有被调用的原因是您永远不会返回第一个 then(...)
的 promise 。
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
});
})
此外,您可能希望在 res
对象上读取 fetchUser(...)
的结果,而不是组件属性。
您应该注意的最后一个警告是,设置状态并在之后立即读取它并不能保证始终按预期工作。安全的做法是将一个函数作为第二个参数传递给 setState
,当 React 更新状态时将调用该函数。
在这种情况下,最简单的方法是避免完全读取状态,而是使用临时变量。
const exists = this.props.exists;
this.setState({
failed: exists
});
if (!exists ) {
return this.props.registerUser(user)
}
关于javascript - 我保证链接正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696909/