reactjs - 如何在 withFormik 中的 handleSubmit 中调度事件
问题描述
对 formik 和 react hook 还是很陌生。
这是我的反应代码。
// react
import React, { useEffect } from 'react';
import { withFormik } from 'formik';
import { useDispatch } from 'redux-react-hook';
import { takeEvery, call, put } from 'redux-saga/effects';
// row, col, field, input, buttonGroup
import {
Row,
Col,
FieldWrapper,
Input,
ButtonGroup
} from 'some-tool';
const searchTypeOption = [
....
];
const SearchForm = (props: any) => {
const {
values,
touched,
errors,
handleChange,
handleSubmit,
} = props;
return (
<form onSubmit={handleSubmit}>
<Row>
<Col md="3">
<FieldWrapper required={true}>
<Select name="searchKey" onChange={handleChange} value={values.searchKey} options={searchTypeOption} />
</FieldWrapper>
{errors.searchKey && touched.searchKey && <div>{errors.searchKey}</div>}
</Col>
<Col md="5">
<FieldWrapper>
<Input
placeholder="Search"
type="text"
onChange={handleChange}
value={values.searchValue}
name="searchValue"
/>
</FieldWrapper>
{errors.searchValue && touched.searchValue && <div>{errors.searchValue}</div>}
</Col>
</Row>
<Row>
<ButtonGroup>
<Button>Clear</Button>
<Button type="submit">Search</Button>
</ButtonGroup>
</Row>
</form>
);
};
export const Search = withFormik({
mapPropsToValues: () => ({ searchKey: '', searchValue: '' }),
// Custom sync validation
validate: values => {
let errors = {};
//if (values.hasOwnProperty('searchKey') && !values.searchKey) {
// errors.searchKey = 'Required';
//}
return errors;
},
handleSubmit: (values, { props, setSubmitting }) => {
const payload = {
searchKey: values.searchKey,
searchValue: values.searchValue
};
// NOTE: obj.props is empty.....
console.log(obj);
// How to use dispatch here or some way to fire event
dispatch({ type: 'SEARCH_DOCS', payload: payload });
},
})(SearchForm);
在中handleSubmit
,我如何调度一个事件,以便 saga 和 redux 能够接收它们?
解决方案
为此,您必须传递一个连接的组件,以便您可以访问调度
像你一样用formik包装这个
const SearchFormFormik = withFormik(SearchForm)
然后连接到redux
const mapDispatchToProps = {
searchDocFun,
};
const ConnectedSearchForm = connect(
null,
mapDispatchToProps
)(SearchFormFormik);
然后您可以在处理提交时使用 searchDocFun
handleSubmit: (values, { props, setSubmitting }) => {
props.searchDocFun(values)
}
推荐阅读
- python - 我如何从用户那里获得接受语言标题?
- python - 如何在 Python 中修复 `pywintypes.com_error`
- php - 在jquery函数中处理单引号和双引号
- ios - 如何将导航栏置于最前面
- python - 导入语句中的点表示什么?
- python - Is it possible to club 2 or more Scripts in Python(spyder)?
- java - Java 泛型 - 类型参数“K”不在其范围内;应该实施 X
- arrays - System Verilog 数组缩减陷阱和参数数组
- python - 如何从响应中获取场地 ID
- mysql - 如何使用nodejs,angularjs在index.html中显示来自mysql的特定数据