问题描述
我在使用 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,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
解决方法
我发现错误。错误在于我的返回函数。它只是将此值返回给 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"}
}