我保证链接正确吗?

问题描述 投票:1回答:1
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(true / false)的状态。

当在第一个promise中调用this.props.registerUser时,它会将this.props.status更改为true。但是,register被设置为false(调用registerUser之前是this.props.status的值),而不是true。

我确定this.props.status正在变为true,但是已注册的状态没有变化。

我是新手。

javascript reactjs redux
1个回答
1
投票

我假设fetchUserregisterUser是返回承诺的函数。在这种情况下,您不需要在fetchUser中包含对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)
}
© www.soinside.com 2019 - 2024. All rights reserved.