axios 提交错误未显示在最终React表上

j8yoct9x  于 2022-12-12  发布在  iOS
关注(0)|答案(2)|浏览(165)

我在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
s4n0splo

s4n0splo1#

我发现了错误。错误在我的返回函数中。它只是将这个值返回给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"}
    }
huwehgph

huwehgph2#

我花了2天在同一个问题(提交错误不显示),并希望张贴我的解决方案在这里的情况下,其他人遇到我的问题,因为我找不到它在网上。
基本上我有一个表单设置如下:

const onSubmit = (values) => {
    ...
    return {username: 'required'} // errors object
}

<Form
  onSubmit={onSubmit}
>
{({values}) => (
  <form>
    <a onClick={() => onSubmit(values)}>save</a>
    ...restOfForm
  </form>
)}
</Form>

上面的问题是我直接调用了“onSubmit”函数,所以返回的提交错误不会出现。我需要调用传递到render函数的“handleSubmit”函数来填充错误,如下所示:

<Form
      onSubmit={onSubmit}
    >
    {({values, handleSubmit}) => (
      <form>
        <a onClick={() => handleSubmit(values)}>save</a>
        ...restOfForm
      </form>
    )}
    </Form>

相关问题