在 Formik React 表单的 handleSubmit 方法中设置 Redux State
Set Redux State in handleSubmit method of Formik React form
我想在提交 Formik 反应表单后通过 Ajax 在 redux 存储中设置一个变量
import React from 'react';
import {connect} from 'react-redux';
import { withFormik, Form, Field } from 'formik';
const LoginForm = ({
values
}) => {
return (
<div>
<Form className={styles.LoginForm}>
<Field className={input_classes} type="text" name="username" placeholder="username" />
<Field className={input_classes} type="password" name="password" placeholder="password" />
<button>Submit</button>
</Form>
</div>
)
}
const mapDispatchToProps = dispatch => {
return {
setData: (data) => dispatch({type: actionTypes.ADD_DATA, data: data})
}
}
const loginForm = connect(null, mapDispatchToProps)(LoginForm);
const FormikLoginForm = withFormik({
mapPropsToValues({ username, password }) {
return {
username: username || '',
password: password || '',
}
},
handleSubmit(values, props) {
//make AJAX call and set data in redux store
}
})(loginForm);
export default FormikLoginForm;
我找不到在 handleSubmit 方法中将任何数据设置到存储的方法;也就是说,如何访问返回 mapDispatchToProps 的 setData 方法?
HOC 的顺序,尤其是在这种情况下(访问另一个 HOC 中的 prop)- redux connect
必须在 withFormik
.
外部
const FormikLoginForm = withFormik({
mapPropsToValues({ username, password }) {
return {
username: username || '',
password: password || '',
}
},
handleSubmit(values, { props } ) {
//make AJAX call and set data in redux store
props.setData( result )
}
})(LoginForm);
export default connect(null, mapDispatchToProps)(FormikLoginForm);
我想在提交 Formik 反应表单后通过 Ajax 在 redux 存储中设置一个变量
import React from 'react';
import {connect} from 'react-redux';
import { withFormik, Form, Field } from 'formik';
const LoginForm = ({
values
}) => {
return (
<div>
<Form className={styles.LoginForm}>
<Field className={input_classes} type="text" name="username" placeholder="username" />
<Field className={input_classes} type="password" name="password" placeholder="password" />
<button>Submit</button>
</Form>
</div>
)
}
const mapDispatchToProps = dispatch => {
return {
setData: (data) => dispatch({type: actionTypes.ADD_DATA, data: data})
}
}
const loginForm = connect(null, mapDispatchToProps)(LoginForm);
const FormikLoginForm = withFormik({
mapPropsToValues({ username, password }) {
return {
username: username || '',
password: password || '',
}
},
handleSubmit(values, props) {
//make AJAX call and set data in redux store
}
})(loginForm);
export default FormikLoginForm;
我找不到在 handleSubmit 方法中将任何数据设置到存储的方法;也就是说,如何访问返回 mapDispatchToProps 的 setData 方法?
HOC 的顺序,尤其是在这种情况下(访问另一个 HOC 中的 prop)- redux connect
必须在 withFormik
.
const FormikLoginForm = withFormik({
mapPropsToValues({ username, password }) {
return {
username: username || '',
password: password || '',
}
},
handleSubmit(values, { props } ) {
//make AJAX call and set data in redux store
props.setData( result )
}
})(LoginForm);
export default connect(null, mapDispatchToProps)(FormikLoginForm);