我有一个通过常规 React 类组件创建的表单,我正在尝试将其迁移到使用"react-final-form"。一切看起来都不错,但无法找到使用具有"反应最终形式"的化简器的方法
最初,我使用 bindActionCreators from react 来映射 Dispatch To Props。所以,它曾经是一个号召性用语文件,一切都很好。 不确定是否有使用相同的功能。我试图直接从onSubmit调用操作,但那里没有定义调度。我什至找不到任何涵盖这部分的教程。
报名表格:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {Link} from 'react-router-dom'
import {Form, Field} from 'react-final-form';
// custom modules
import { submitEmail } from '../../actions/submitEmail';
import '../../styles/custom.css';
//Form through react-final-form
const renderInput = ({input, meta}) => (
<input {...input} type="text" errorMessage={meta.touched && meta.error} />
);
const onSubmit = values => {
debugger;
submitEmail('/freeTrial', values);
console.log("put request sent for trial ")
alert(JSON.stringify(values))
};
const required = v => {
console.log("v....: ", v);
if (!v || v === ''){
return 'This field is required';
}
return undefined;
};
const SendEmailInfo = () => (
<Form
onSubmit={onSubmit}
render={({handleSubmit, invalid}) => (
<div>
<h2>Request 30 days Free Trial</h2>
<form onSubmit={handleSubmit} >
<Field name="customer-id"
component={renderInput}
validate={required} />
<button type="submit" disabled={invalid} > Submit </button>
</form>
</div>
)}
/>
);
const mapDispatchToProps = dispatch => {
return bindActionCreators(
{ submitEmail }, dispatch);
};
export default connect(null, mapDispatchToProps)(SendEmailInfo)
提交电子邮件
import { API_URL } from '../global';
export const makeAPIRequestToSendEmail = () => {
return {
type: 'MAKE_API_REQUEST_TO_SEND_EMAIL'
};
};
export const clearEmailDetails = () => {
return {
type: 'CLEAR_EMAIL_DETAILS'
};
};
export const receivedResponse = () => {
return {
type: 'RECEIVED_RESPONSE'
};
};
export const sentEmail = data => {
return {
type: 'SENT_EMAIL',
data
};
};
export const errorEmail = () => {
return {
type: 'ERROR_EMAIL'
};
};
export function submitEmail(url, data) {
return dispatch => {
dispatch(makeAPIRequestToSendEmail());
dispatch(clearEmailDetails());
return fetch(API_URL + url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ data })
})
.then(response => response.json())
.then(emailMessage => {
dispatch(receivedResponse());
console.log(emailMessage);
dispatch(sentEmail(emailMessage));
})
.catch(err => dispatch(errorEmail()));
}
}
我想使用操作和化简器,让它处理所有 API 请求。如果您有任何解决此难题的建议,请告诉我。
React Final Form 所关心的只是你给它一个返回 Promise 的onSubmit
。我已经编写了一个库来使用可能适合您特定需求的 Redux 操作来执行此操作?
React Redux Promise Listener