我正在使用redux-form。我有一个onSubmit
和一个checkStatus
方法,它们都对API后端进行Ajax调用。如果Ajax调用的结果不是200,我想抛出一个SubmissionError。
如果我将它放在onSubmit
中,它会正常工作(它正确地向我显示了表单上的错误消息)。但是如果我把它扔到checkStatus
里面,那么我会收到一个抱怨处理异常的错误:
Uncaught (in promise) SubmissionError {errors: {…}, message: "Submit
Validation Failed", name: "SubmissionError", stack: "SubmissionError:
Submit Validation Failed at ...) at <anonymous>"}
我确实看到this comment让你看起来只应该从SubmissionError
内投掷onSubmit()
:
这是我的代码:
import * as React from "react";
import { reduxForm, touch, Form, SubmissionError } from 'redux-form';
import ReduxFormField from './components/ReduxFormField'
export interface FormProps {
handleSubmit: any;
error: any;
}
export class MyForm extends React.Component<FormProps, any> {
private _inputVal: any;
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.checkStatus = this.checkStatus.bind(this);
}
checkStatus() {
return fetch("/checkStatus", {
method: 'GET',
}).then(response => {
if (response.status === 200) {
// checkStatus was successful!
} else {
throw new SubmissionError({
_error: "There was an error."
});
}
});
}
onSubmit(event) {
return fetch("/submit", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({'key1': 'val1'})
}).then(response => {
if (response.status === 200) {
// submit was successful!
} else {
throw new SubmissionError({
_error: "There was an error."
});
}
});
}
render() {
return (
<form onSubmit={this.props.handleSubmit(this.onSubmit)}>
<div>
<fieldset>
<ReduxFormField
type="text" fieldName="myInputValue"
ref={(input) => {
this._inputVal = input;
}}/>
</fieldset>
<input type="submit" value="Submit"/>
<a onClick={() => {
this.checkStatus()
}
}>Check Status
</a>
</div>
</form>
)
}
}
export default reduxForm({
form: 'myForm'
})(MyForm);
答案 0 :(得分:0)
我想这个动作创作者应该提供帮助
setSubmitFailed(form:String, ...fields:String) #
Flips submitFailed flag true, removes submitSucceeded and submitting, marks all the fields passed in as touched, and if at least one field was passed flips anyTouched to true.
另一个选项是创建一个formField(我不是指一个可见字段,而只是在redux-form中),默认情况下调用'checkStatus'为true。当您的检查失败时,只需将名为change
的操作发送到此字段,并为reduxForm提供验证器,如果字段为false,则验证器将失败