我在我的React / Redux应用程序中使用redux-form,并且试图弄清楚如何在提交时分派一个动作。
我已经能够触发handleSubmit函数,并且执行传递给它的Submit函数,但是未调用'submitFormValues'操作。
我试过使用mapDispatchToProps和connect(),但这也不起作用。
Redux-Form操作执行(START_SUBMIT,STOP_SUBMIT,SET_SUBMIT_SUCCEEDED),但是我自己的操作创建者从未执行过。
形式如下:
import React from "react";
import { Field, reduxForm } from "redux-form";
import {submitFormValues} from "../../../actions/BasicFormActions";
function submit(values) {
//Can log the values to the console, but submitFormValues actionCreator does not appear to be dispatched.
return new Promise(function(resolve) { resolve(submitFormValues(values))} )
}
const renderField = ({ input, label, type, meta: {touched, error} }) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type}/>
{touched && error && <span>{error}</span>}
</div>
</div>
)
const BasicForm = (props) => {
const { error, handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit(submit)}>
<Field name="firstName" type="text" component={renderField} label="First Name"/>
<Field name="lastName" type="text" component={renderField} label="Last Name"/>
{error && <strong>{error}</strong>}
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear</button>
</div>
</form>
)
}
export default reduxForm({
form: "basicForm",
submit
})(BasicForm)
这是动作创建者(使用Thunk)。我能够成功地调度这些操作,而不仅仅是从表单中进行。
export const submitFormValues = (values) => (dispatch) =>
getData("submitApproveForm", values).then(response => {
dispatch(formSubmissionError(response))
}).catch(error => {
throw (error);
});
const formSubmissionError = (response) =>
({
type: types.FORM_SUBMISSION_ERROR,
basicFormResponse: { ...response}
});
export const getData = (apiName, args) =>
fetch(settings.basePath + getUrl(apiName, args))
.then(response =>
response.json()
).catch(error => {
return error;
});
最后是我的减速器:
import * as types from "../actions/ActionsTypes";
import initialState from "./initialState";
const basicFormReducer = (state = initialState.basicFormResponse, action) => {
switch (action.type) {
case types.FORM_SUBMISSION_ERROR:
return {...state, "errors": action.basicFormResponse}; // returns a new state
case types.FORM_SUBMISSION_SUCCESS:
return {...state, "successes": action.basicFormResponse}; // returns a new state
default:
return state;
}
};
export default basicFormReducer;
预先感谢您的帮助。
最佳答案
Redux Form在onSubmit
回调中不调度任何内容。这是因为我们不假设您希望如何处理表单提交。
但是,您可以use the dispatch
argument并...调度您的动作!
function submit(values, dispatch) {
return dispatch(submitFormValues(values));
}