首页 > 解决方案 > 我承诺正确链接吗?

问题描述

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,但已注册的状态没有更改。

我对这个东西很陌生。

标签: javascriptreactjsredux

解决方案


我假设fetchUserandregisterUser是返回承诺的函数。在这种情况下,您不需要将调用包装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)
}

推荐阅读