我有一个通过常规React类组件创建的表单,我正尝试将其迁移为使用“ react-final-form”。一切看起来都不错,但找不到找到将减速器与“反应最终形式”一起使用的方法
最初,我使用bindActionCreators从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请求。如果您有任何解决此难题的建议,请告诉我。
答案 0 :(得分:1)
所有React Final Form关心的是您给它一个onSubmit
来返回一个Promise。我已经编写了一个库来通过Redux动作来满足您的特定需求?