在Redux Forms中提交表单前进行派单可以通过以下步骤实现(使用TypeScript):
// actions.ts
import { Dispatch } from 'redux';
export const submitForm = (formData: any) => {
return async (dispatch: Dispatch) => {
// 派单前的操作,例如发送网络请求
dispatch({ type: 'SUBMIT_FORM_REQUEST' });
try {
// 执行异步操作,例如发送网络请求或调用API
const response = await fetch('https://api.example.com/submit', {
method: 'POST',
body: JSON.stringify(formData),
});
// 派单成功后的操作
dispatch({ type: 'SUBMIT_FORM_SUCCESS', payload: response.data });
} catch (error) {
// 派单失败后的操作
dispatch({ type: 'SUBMIT_FORM_FAILURE', payload: error.message });
}
};
};
// reducer.ts
import { combineReducers } from 'redux';
const initialState = {
isSubmitting: false,
error: null,
};
const formReducer = (state = initialState, action: any) => {
switch (action.type) {
case 'SUBMIT_FORM_REQUEST':
return { ...state, isSubmitting: true, error: null };
case 'SUBMIT_FORM_SUCCESS':
return { ...state, isSubmitting: false };
case 'SUBMIT_FORM_FAILURE':
return { ...state, isSubmitting: false, error: action.payload };
default:
return state;
}
};
const rootReducer = combineReducers({
form: formReducer,
});
export default rootReducer;
// FormComponent.tsx
import React from 'react';
import { Field, reduxForm, InjectedFormProps } from 'redux-form';
import { connect } from 'react-redux';
import { submitForm } from './actions';
interface FormData {
// 定义表单字段的类型
name: string;
email: string;
// 其他表单字段...
}
const FormComponent: React.FC<InjectedFormProps<FormData>> = (props) => {
const { handleSubmit, submitting, dispatch } = props;
const onSubmit = (formData: FormData) => {
// 派发派单的action
dispatch(submitForm(formData));
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name</label>
<Field name="name" component="input" type="text" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field name="email" component="input" type="email" />
</div>
{/* 其他表单字段... */}
<button type="submit" disabled={submitting}>
Submit
</button>
</form>
);
};
const ConnectedFormComponent = connect()(reduxForm<FormData>({
form: 'myForm',
})(FormComponent));
export default ConnectedFormComponent;
通过以上步骤,我们可以在Redux Forms中实现在提交表单前进行派单的操作。在派单的action中,可以执行一些异步操作,并根据派单的状态更新Redux的store。这样可以实现更复杂的表单提交流程,例如发送网络请求或调用API,并根据派单的结果更新应用的状态。
请注意,以上示例中的代码仅供参考,具体实现可能会根据项目的需求和架构进行调整。