Reactjs Formik复选框导致检查延迟太多#1901

Reactjs Formik复选框导致检查延迟太多#1901,reactjs,checkbox,ecmascript-6,formik,yup,Reactjs,Checkbox,Ecmascript 6,Formik,Yup,无论何时我选中或取消选中,React-Formik-Yup复选框都会导致如此多的延迟。 这是我的问题的代码沙盒- 我对我的复选框组使用了两种方法,但都没有按预期工作。 一种是通过将handleCheckBox方法绑定到构造函数,另一种是直接使用Formik的handleChange 请帮我解决这个问题 import React, { Component } from "react"; import { Formik, Form, Field, ErrorMessage } from "form

无论何时我选中或取消选中,React-Formik-Yup复选框都会导致如此多的延迟。 这是我的问题的代码沙盒-

我对我的复选框组使用了两种方法,但都没有按预期工作。 一种是通过将handleCheckBox方法绑定到构造函数,另一种是直接使用Formik的handleChange

请帮我解决这个问题

import React, { Component } from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

// form constants
const restaurantTypeOptions = ["Delivery", "Take away", "Dine in"];
const restaurantSuitedOptions = ["Family", "Couple", "Cafe"];
const debug = true;

class SignUp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      restTypeArr: [],
      restSuitArr: []
    };
    this.handleCheckBox = this.handleCheckBox.bind(this);
  }

  handleCheckBox(e) {
    const newSelection = e.target.value;
    let newSelectionArray;

    if (Formik.values.restaurantType.indexOf(newSelection) > -1) {
      newSelectionArray = Formik.values.restaurantType.filter(
        s => s !== newSelection
      );
    } else {
      newSelectionArray = [...Formik.values.restaurantType, newSelection];
    }

    this.setState(prevState => ({
      restTypeArr: newSelectionArray
    }));
  }

  render() {
    return (
      <div id="signupContainer" className="signinup-container">
        <h3 className="mb-4"> Sign Up </h3>
        <Formik
          initialValues={{
            //restaurantType: ['Delivery', 'Take away'],
            restaurantType: this.state.restTypeArr,
            restaurantSuited: []
          }}
          validationSchema={Yup.object().shape({
            restaurantType: Yup.array().required("Please select at least one"),
            restaurantSuited: Yup.array().required("Please select at least one")
          })}
          onSubmit={(values, { resetForm, setErrors, setSubmitting }) => {
            setTimeout(() => {
              console.log("Getting form values - ", values);
            }, 500);
          }}
          enableReinitialize={true}
        >
          {props => {
            const {
              values,
              touched,
              errors,
              isSubmitting,
              handleChange,
              handleBlur,
              setFieldValue
            } = props;

            return (
              <Form id="signUpForm" className="signinupForm" noValidate>
                <div className="form-group">
                  <label className="form-label" htmlFor="restaurantType">
                    Restaurant Type
                  </label>
                  <div className="checkbox-group">
                    {restaurantTypeOptions.map((option, index) => {
                      return (
                        <label
                          key={option}
                          index={index}
                          className="checkbox-inline"
                        >
                          <Field
                            type="checkbox"
                            name="restaurantType"
                            value={option}
                            id={option}
                            checked={values.restaurantType.indexOf(option) > -1}
                            onChange={this.handleCheckBox}
                          />
                          {option}
                        </label>
                      );
                    })}
                  </div>
                  <ErrorMessage
                    name="restaurantType"
                    component="span"
                    className="invalid-input"
                  />
                </div>
                {/* Restaurant Type */}

                <div className="form-group">
                  <label className="form-label" htmlFor="restaurantSuited">
                    Restaurant Suited for
                  </label>
                  <div className="checkbox-group">
                    {restaurantSuitedOptions.map(option => {
                      return (
                        <label key={option} className="checkbox-inline">
                          <Field
                            type="checkbox"
                            name="restaurantSuited"
                            value={option}
                            checked={
                              values.restaurantSuited.indexOf(option) > -1
                            }
                            //onChange={() => setFieldValue("restaurantSuited", option)}
                            onChange={() => {
                              if (values.restaurantSuited.includes(option)) {
                                values.restaurantSuited.pop(option);
                              } else {
                                values.restaurantSuited.push(option);
                              }
                            }}
                          />
                          {option}
                        </label>
                      );
                    })}
                  </div>
                  <ErrorMessage
                    name="restaurantSuited"
                    component="span"
                    className="invalid-input"
                  />
                </div>
                {/* Restaurant Suited */}

                <button
                  type="submit"
                  className="btn btn-filled"
                  disabled={isSubmitting}
                >
                  SignUp
                </button>
                {/*Submit */}

                {debug && (
                  <>
                    <pre style={{ textAlign: "left" }}>
                      <strong>Values</strong>
                      <br />
                      {JSON.stringify(values, null, 2)}
                    </pre>
                    <pre style={{ textAlign: "left" }}>
                      <strong>Errors</strong>
                      <br />
                      {JSON.stringify(errors, null, 2)}
                    </pre>
                  </>
                )}
              </Form>
            );
          }}
        </Formik>
      </div>
    );
  }
}

export default SignUp;

import React,{Component}来自“React”;
从“Formik”导入{Formik,Form,Field,ErrorMessage};
从“Yup”导入*作为Yup;
//形式常数
const restaurantTypeOptions=[“送货”、“外卖”、“进餐”];
const RestaurantSiteDoptions=[“家庭”、“夫妻”、“咖啡馆”];
const debug=true;
类注册扩展了组件{
建造师(道具){
超级(道具);
此.state={
restTypeArr:[],
restSuitArr:[]
};
this.handleCheckBox=this.handleCheckBox.bind(this);
}
手电筒(e){
const newSelection=e.target.value;
让新闻自由传播;
if(Formik.values.restaurantType.indexOf(newSelection)>-1){
newSelectionArray=Formik.values.restaurantType.filter(
s=>s!==newSelection
);
}否则{
newSelectionArray=[…Formik.values.restaurantType,newSelection];
}
this.setState(prevState=>({
restypearr:newSelectionArray
}));
}
render(){
返回(
注册
{
设置超时(()=>{
log(“获取表单值-”,值);
}, 500);
}}
enableReinitialize={true}
>
{props=>{
常数{
价值观
感动的,
错误,
提交,
handleChange,
车把,
setFieldValue
}=道具;
返回(
餐厅类型
{restaurantTypeOptions.map((选项,索引)=>{
返回(
-1}
onChange={this.handleCheckBox}
/>
{option}
);
})}
{/*餐厅类型*/}
适合
{restaurantsitedoptions.map(选项=>{
返回(
-1
}
//onChange={()=>setFieldValue(“restaurantsited”,选项)}
onChange={()=>{
if(值。餐厅项目包括(选项)){
value.restaurantsited.pop(可选);
}否则{
值。RestaurantSited.push(选项);
}
}}
/>
{option}
);
})}
{/*餐厅*/}
报名
{/*提交*/}
{调试&&(


{JSON.stringify(值,null,2)} 错误
{JSON.stringify(错误,null,2)} )} ); }} ); } } 导出默认注册;
我可能会解释错误,如果有人能纠正我,请这样做

通过使用
checked
,复选框将被设置为该值,但不能更改
值。restaurantType.indexOf(选项)>-1
该值将被永久保留,如果您打算设置默认检查,请使用
defaultChecked

否则,您必须将state与
onChange一起使用


我可以看到您使用了onChange with state,但是
values.restaurantType.indexOf(option)>-1的值是用props映射的,但是由于props是不可变的,因此该值将永远不会更改

删除这一行
checked={values.restaurantType.indexOf(option)>-1}
,它永远不会更改Hanks@Michael。但是你能解释一下原因吗?当然可以,但是因为我会在评论中使用限制这个词answer@Gaurav你能澄清一下你想要实现什么吗?非常感谢@Michael。如果您也能调查一下我在过去3天里一直在处理的这个问题,我将不胜感激嗨,迈克尔,请帮我解决这个问题-