我在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;
提前感谢您的帮助。
答案 0 :(得分:13)
Redux Form不会在onSubmit
回调中发送任何内容。这是因为我们不会假设您希望如何处理表单提交。
但是,您可以use the dispatch
argument并......发送您的行动!
function submit(values, dispatch) {
return dispatch(submitFormValues(values));
}