承诺redux表单onSubmit函数

时间:2018-09-05 06:54:21

标签: javascript redux promise react-redux redux-form

我想使我的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') };
}

2 个答案:

答案 0 :(得分:1)

我相信您在想这是错误的方式。提交表单后redux-form already has a mechanism for handling promises(“承诺”)。从文档中:

  

如果onSubmit函数返回一个Promise,则在将Promise解析或拒绝之前,submitting属性将设置为true。如果它被包含格式为{field1:'error',field2:'error'}的错误的redux形式的SubmissionError拒绝,则提交错误将被添加到每个字段(错误道具),就像异步验证错误是。如果存在不是特定于任何字段但适用于整个表单的错误,则可以将其传递给_error字段,就好像它是错误一样,并将其作为错误属性给出。

这将起作用:

// 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

答案 1 :(得分:0)

使用submit()时,您需要让dispatch(submit())返回一个thunk,以便Promise返回react-redux

const submit = () => {
  return (dispatch, getState) => {
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

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

当前它返回的是Promise,这不是redux-thunk所需要的。相反,您需要返回一个返回Promise 的函数