如何将简单的Formik表单与Redux存储连接并发送一个动作?

时间:2017-11-21 18:38:34

标签: javascript reactjs redux react-redux formik

我是react / redux的新手,但可以为我的应用程序实现一些简单的addProduct表单。 今天我尝试用Formik中的Basic demo替换它,但是我不明白我应该在哪里放置“调度”功能(我在任何地方都尝试过)。

可能是我以错误的方式使用连接?

我的新组件与Demo完全相同,只不过我用productName(以及其他附加字段)替换了电子邮件。但我无法理解如何将“值”从Formik传递到Redux商店。

我没有Formik的旧表单组件如下所示:

import React from 'react';
import { connect } from 'react-redux';
import { addProduct } from '../actions';

const AddProduct0 = ({ dispatch }) => {
  let inputSKUNumber;
  let inputProductName;
  return (
    <div>
      <input
        ref={(node) => {
          inputSKUNumber = node;
        }}
        placeholder="SKU Number"
      />
      <input
        ref={(node) => {
          inputProductName = node;
        }}
        placeholder="Product name"
      />
      <button
        onClick={() => {
          dispatch(addProduct({ SKUNumber: inputSKUNumber.value, name: inputProductName.value }));
          inputSKUNumber.value = '';
          inputProductName.value = '';
        }}
      >
        Add Product
      </button>
    </div>
  );
};
const AddProduct = connect()(AddProduct0);

export default AddProduct;

我使用formik的新组件如下所示:

import React from 'react';
import { connect } from 'react-redux';
import { withFormik } from 'formik';
import Yup from 'yup';
import { addProduct } from '../actions';
import './helper.css';

// Our inner form component. Will be wrapped with Formik({..})
const MyInnerForm = (props) => {
  const {
    values,
    touched,
    errors,
    dirty,
    isSubmitting,
    handleChange,
    handleBlur,
    handleSubmit,
    handleReset,
  } = props;
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="SKUNumber">SKU Number</label>
      <input
        id="SKUNumber"
        placeholder="SKU Number"
        type="number"
        value={values.SKUNumber}
        onChange={handleChange}
        onBlur={handleBlur}
        className={errors.SKUNumber && touched.SKUNumber ? 'text-input error' : 'text-input'}
      />
      <div className="input-feedback">{touched.SKUNumber ? errors.SKUNumber : ''}</div>

      <label htmlFor="productName">Product Name</label>
      <input
        id="productName"
        placeholder="Product Name"
        type="text"
        value={values.productName}
        onChange={handleChange}
        onBlur={handleBlur}
        className={errors.productName && touched.productName ? 'text-input error' : 'text-input'}
      />
      <div className="input-feedback">{touched.productName ? errors.productName : ''}</div>


      <button
        type="button"
        className="outline"
        onClick={handleReset}
        disabled={!dirty || isSubmitting}
      >
        Reset
      </button>
      <button type="submit" disabled={isSubmitting}>
        Submit
      </button>

      <DisplayFormikState {...props} />
    </form>
  );
};

const EnhancedForm = withFormik({
  mapPropsToValues: () => ({
    SKUNumber: 12345678,
    productName: 'Default Product',
  }),

  validationSchema: Yup.object().shape({
    SKUNumber: Yup.number()
      .max(99999999, 'SKU Number must be less than 8 digits')
      .required('SKU Number is required!'),

    productName: Yup.string()
      .min(5, 'Product name must be longer than 5 symbols')
      .max(50, 'Product name must be shorter than 50 symbols')
      .required('Product name is required!'),

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 1000);
    // dispatch(addProduct(values));
  },
  displayName: 'BasicForm', // helps with React DevTools
})(MyInnerForm);

export const DisplayFormikState = props => (
  <div style={{ margin: '1rem 0' }}>
    <h3 style={{ fontFamily: 'monospace' }} />
    <pre
      style={{
        background: '#f6f8fa',
        fontSize: '.65rem',
        padding: '.5rem',
      }}
    >
      <strong>props</strong> = {JSON.stringify(props, null, 2)}
    </pre>
  </div>
);

const AddProduct = connect()(EnhancedForm);

export default AddProduct;

P.S。如果有人在这里添加标签“formik”,请执行此操作。

3 个答案:

答案 0 :(得分:8)

我还在formik页面上打开了一个问题。其中一位贡献者给了我答案。所有都与该代码一起使用:

&#13;
&#13;
handleLoginFormSubmit() {
  // send axios request to controller and from controller to gRPC
  axios.post('/loginUser', this.login)
    .then((response) => {
      this.userData = JSON.parse(response.data[0]);
      this.$store.dispatch('loginUser',this.userData);
    })
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
import React from 'react';
import { connect } from 'react-redux';
import { addProduct } from '../actions';

/* AddProduct не совсем контейнер, он просто вызывает диспатч,
  ему не нужен стор, поэтому мы можем создать коннект коротким путем:
  AddProduct = connect()(AddProduct); */
const AddProduct = ({ addMyProduct }) => {
  let inputSKUNumber;
  let inputProductName;
  return (
    <div>
      <input
        ref={(node) => {
          inputSKUNumber = node;
        }}
        placeholder="SKU Number"
      />
      <input
        ref={(node) => {
          inputProductName = node;
        }}
        placeholder="Product name"
      />
      <button
        onClick={() => {
          addMyProduct({ SKUNumber: inputSKUNumber.value, name: inputProductName.value });
          inputSKUNumber.value = '';
          inputProductName.value = '';
        }}
      >
        Add Product
      </button>
    </div>
  );
};

const mapDispatchToProps = dispatch => ({
    addMyProduct: (params) => dispatch(addProduct(params))
});

export default connect(null, mapDispatchToProps)(AddProduct);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用更高的变量或异步函数。较高的变量有点la脚但是可以使用。

let setSubmittingHigher;
// Our inner form component. Will be wrapped with Formik({..})
const MyInnerForm = (props) => {enter code here

.
.
.

    handleSubmit(values, {props, setSubmitting}) {
        setSubmittingHigher = setSubmitting;

.
.
.

const mapStateToProps = (state) => {
    typeof setSubmittingHigher === 'function' && setSubmittingHigher(false);
    return {}
};

const mapDispatchToProps = dispatch => ({
    addMyProduct: (params) => dispatch(addProduct(params))
});

export default connect(mapStateToProps, mapDispatchToProps)(AddProduct);