首页 文章

我保证链接正确吗?

提问于
浏览
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,但是已注册的状态没有变化 .

我是新手 .

1 回答

  • 1

    我假设 fetchUserregisterUser 是返回promises的函数 . 在这种情况下,您不需要在 new Promise(...) 中包装 fetchUser 的调用,因为它将在调用时返回一个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
            });
        })
    

    此外,您希望在 res 对象上读取 fetchUser(...) 的结果而不是组件道具 .

    您应该注意的最后一点需要注意的是,设置状态并在之后立即读取状态并不能保证始终按预期工作 . 这样做的安全方法是将函数作为第二个参数传递给 setState ,并在React更新状态时调用该函数 .

    在这种情况下,最简单的方法是避免完全读取状态,而是使用临时变量 .

    const exists = this.props.exists;
    this.setState({
        failed: exists
    });
    if (!exists ) {
        return this.props.registerUser(user)
    }
    

相关问题