1

我在使用 React-Final-Form 库时遇到问题。从onSubmit函数中,我返回了一个验证错误,但它没有显示在表单本身上。在这里你可以看到我的代码:

我的表格:

<Form
                                       onSubmit={this.onSubmit}
                                        initialValues={{}}
                                        validate={
                                            values => {
                                                const errors = {}
                                                if (!values.username) {
                                                    errors.username = "This field is required"
                                                }
                                                if (!values.password) {
                                                    errors.password = "This field is required"
                                                }
                                                return errors
                                            }
                                        }
                                        render={({submitError, handleSubmit, submitting, values}) => (
                                            <form onSubmit={handleSubmit}>
                                                <div className="form-group">
                                                    <label>First Name</label>
                                                    <Field name="username">
                                                        {({input, meta}) => (
                                                            <>
                                                                <input {...input} type="text" placeholder="Username"
                                                                       className={"form-control" + ((meta.error || meta.submitError) && meta.touched ? " is-invalid" : "")}/>
                                                                {(meta.error || meta.submitError) && meta.touched ?
                                                                    <div
                                                                        className="invalid-feedback">{meta.error || meta.submitError}</div> : null
                                                                }
                                                            </>
                                                        )}
                                                    </Field>
                                                    {submitError && (
                                                        <div>{submitError}</div>
                                                    )}
                                                </div>
                                                <div className="form-group">
                                                    <label>Password</label>
                                                    <Field name="password">
                                                        {({input, meta}) => (
                                                            <>
                                                                <input {...input} type="password"
                                                                       placeholder="Password"
                                                                       className={"form-control" + ((meta.error || meta.submitError) && meta.touched ? " is-invalid" : "")}/>
                                                                {(meta.error || meta.submitError) && meta.touched ?
                                                                    <div
                                                                        className="invalid-feedback">{meta.error || meta.submitError}</div> : null
                                                                }
                                                            </>
                                                        )}
                                                    </Field>
                                                </div>
                                                <button type="submit" disabled={submitting}
                                                        className="btn btn-block btn-outline-secondary">Log In
                                                </button>
                                                <pre>{JSON.stringify(values, 0, 2)}</pre>
                                            </form>
                                        )}
                                    />

我的 onSubmit 函数:

onSubmit = async values => {
        const errors = {}
        let loginData = {
            username: values.username,
            password: values.password
        }
        usersAPI.getCSRF().then((response) => {
            usersAPI.login(loginData)
                .then(response => {
                    if (response.data.login_status === "Incorrect data") {
                        console.log("Invalid data")
                        errors.username = "Invalid login or password"
                        errors.password = "Invalid login or password"
                        return errors
                    } else {
                        localStorage.setItem('token', response.data.token)
                        this.props.setAuthState(true)
                        console.log("Logged in successfully")
                    }
                })
                .catch(err => console.log(err))
        })
    }

问题出在 axios 请求中。如果我的后端服务器发送凭据无效的响应,console.log("Invalid data")则会出现在控制台中,但表单不会发生任何事情。如果我评论我的 axios 请求并留下以下代码:

onSubmit = async values => {
        return {username: "Invalid data"}
    }

因此,在这种情况下,一切正常。谁能告诉我如何优化我的 axios 请求,以便之后我的表单将收到从返回的提交错误

errors.username = "Invalid login or password"
errors.password = "Invalid login or password"
return errors
4

1 回答 1

2

我发现了错误。错误出现在我的返回函数中。它只是将此值返回给 usersAPI.getCSRF()函数,而不是全局onSubmit函数。我做了一些更改,所以我的最终代码如下所示:

onSubmit = values => {
        let loginData = {
            username: values.username,
            password: values.password
        }
        let success = false;
        usersAPI.getCSRF().then((response) => {
            usersAPI.login(loginData)
                .then(response => {
                    if (response.data.login_status !== "Incorrect data") {
                        success = true
                        localStorage.setItem('token', response.data.token)
                    }
                })
                .catch(err => console.log(err))
        })
        if (success) this.props.setAuthState(true)
        else return {username: "Incorrect username or password", password: "Incorrect username or password"}
    }
于 2021-01-24T10:45:48.390 回答