如何在句柄中调度事件Submit in with Formik



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 能够接收它们?

为此,

您必须传递连接的组件,以便可以访问调度

像你一样用福米克包装它

const SearchFormFormik = withFormik(SearchForm) 

然后将其连接到 redux

const mapDispatchToProps = {
  searchDocFun,
};
const ConnectedSearchForm = connect(
  null,
  mapDispatchToProps
)(SearchFormFormik);

然后你可以使用搜索文档乐趣在句柄提交

handleSubmit: (values, { props, setSubmitting }) => {
        props.searchDocFun(values)
    }

最新更新