gpt4 book ai didi

javascript - Promise 一个 redux 表单 onSubmit 函数

转载 作者:行者123 更新时间:2023-12-03 01:11:58 24 4
gpt4 key购买 nike

我想让我的submitForm能够保证redux表单的onSubmit处理。

与此处找到的示例相同https://redux-form.com/7.1.2/examples/submitvalidation/

submitForm = () => {
return this.props.submituserForm()
.then(() => { console.log('test') })
.catch(() => { console.log('error') })
}

-----------------------------------


const mapDispatchToProps = (dispatch) => {
// i want to promisify submituserForm to behave like the sleep
// function below
return {
submituserForm: () => dispatch(submit())
}
};

////////////////////////////////////////////////////


// this part is working fine
const submit = () => {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// simulate server latency
return sleep(5000)
.then(() => { console.log('test') };
}

最佳答案

我相信您的思考方式是错误的。 redux-form already has a mechanism for handling promises (“ promise ”)提交表格时。来自文档:

If your onSubmit function returns a promise, the submitting property will be set to true until the promise has been resolved or rejected. If it is rejected with a redux-form SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then the submission errors will be added to each field (to the error prop) just like async validation errors are. If there is an error that is not specific to any field, but applicable to the entire form, you may pass that as if it were the error for a field called _error, and it will be given as the error prop.

这会起作用:

// submit.js
import { SubmissionError } from "redux-form";

export const submit = (values, dispatch, props) => {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// simulate server latency
return sleep(5000)
.then(() => { console.log('test') })
.catch(() => {
console.error('error');
throw new SubmissionError({ _error: 'There was an error submitting.' });
});
}

// MyForm.js
import React from "react";
import { reduxForm, ... } from "redux-form";
import { submit } from "submit";

class MyForm extends React.Component {
...
render() {
const { error, handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
...
{error && <strong>{error}</strong>}
<button type="submit" value="Submit">Submit</button>
</form>
)
}
};

export default reduxForm({
form: "MyForm",
onSubmit: submit
})(MyForm);

参见this example有关如何处理提交表单时的 promise 的更详细说明。

关于javascript - Promise 一个 redux 表单 onSubmit 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com