Formikでエントリを編集すると、Yupは既存のフィールドを認識しません

Aug 22 2020

フィールドが正しく、すべてが導入されているかどうかを確認するために、エンティティ(この場合は会社)を作成するときにFormikとYupを使用しています(すべて必須)。

エンティティを作成すると、正常に機能します。すべてのフィールドが導入され、ルールが満たされている場合にのみエンティティを作成できます(現時点ではメールのルールは1つだけです)。

これは、名前と電子メールの2つのフィールドを持つ新しい会社を作成するために機能するコードです。

    import React from 'react';
    import { Redirect } from 'react-router-dom';
    import { Formik, Form, Field } from 'formik';
    import { Input, Button, Label, Grid } from 'semantic-ui-react';
    import { connect } from 'react-redux';
    import * as Yup from 'yup';
    import { Creators } from '../../../actions';
    import Layout from '../../Layout/Layout';
    
    class CreateCompanyForm extends React.PureComponent {
      constructor(props) {
        super(props);
    
        this.state = {
          name: '',
          contactMail: '',
          redirectCreate: false,
          redirectEdit: false,
          edit: false,
        };
      }
    
      componentDidMount() {
        const {
          getCompany,
          location: { pathname },
        } = this.props;
      }
    
      handleSubmit = values => {
        const { createCompany, getCompanies } = this.props;
        createCompany(values);
        this.setState({ redirectCreate: true });
        getCompanies(this.props.query);
      };
    
      render() {
        let title = 'Create Company';
        let buttonName = 'Create';
        let submit = this.handleSubmitCreate;
    
        const { redirectCreate, redirectEdit } = this.state;
    
        if (redirectCreate) {
          return <Redirect to="/companies" />;
        }
        const initialValues = {
          name: '',
          contactMail: '',
        };
        const requiredErrorMessage = 'This field is required';
        const emailErrorMessage = 'Please enter a valid email address';
        const validationSchema = Yup.object({
          name: Yup.string().required(requiredErrorMessage),
          contactMail: Yup.string()
            .email(emailErrorMessage)
            .required(requiredErrorMessage),
        });
        return (
          <Layout>
            <div>
              <Button type="submit" form="amazing">
                Create company
              </Button>
              <Button onClick={() => this.props.history.goBack()}>Discard</Button>
              <div>Create company</div>
            </div>
    
            <Formik
              htmlFor="amazing"
              initialValues={initialValues}
              validationSchema={validationSchema}
              onSubmit={values => this.handleSubmit(values)}>
              {({ values, errors, touched, setValues }) => (
                <Form id="amazing">
                  <Grid columns={2}>
                    <Grid.Column>
                      <Label>Company Name</Label>
                      <Field name="name" as={Input} placeholder="Hello" />
                      <div>{touched.name && errors.name ? errors.name : null}</div>
                    </Grid.Column>
    
                    <Grid.Column>
                      <Label>Contact Mail</Label>
                      <Field
                        name="contactMail"
                        as={Input}
                        placeholder="[email protected]"
                      />
                      <div>
                        {touched.contactMail && errors.contactMail
                          ? errors.contactMail
                          : null}
                      </div>
                    </Grid.Column>
                  </Grid>
                </Form>
              )}
            </Formik>
          </Layout>
        );
      }
    }
    
    const mapStateToProps = state => ({
      companies: state.companies.companies,
      company: state.companies.selectedCompany,
      query: state.companies.query,
    });
    
    const mapDispatchToProps = {
      getCompanies: Creators.getCompaniesRequest,
      createCompany: Creators.createCompanyRequest,
      getCompany: Creators.getCompanyRequest,
      updateCompany: Creators.updateCompanyRequest,
    };

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

会社を編集したいときに問題が発生します。したがって、誰かが編集ボタンで会社をクリックすると、編集可能である必要がある現在の値を含むすべてのフィールドで会社を開く必要があります。

状態を使用しているこれらの現在の値を取得するには、たとえば、電子メールにアクセスしてthis.state.email、値を変更するために追加されたonChangeメソッドを使用できます。

値はテキスト入力で変更できます。ただし、データが含まれている場合でもフィールドが必須であるというYupメッセージがトリガーされます。これはなぜ発生するのですか?フィールドは空ではありません。それは、そのメッセージを表示する必要がある状況です。

そしてもちろん、クリックして保存してもエンティティは更新されません。これらのフィールドが必要なためです。

コードは次のとおりです。

import React from 'react';
...

class CreateCompanyForm extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      name: '',
      contactMail: '',
      redirectCreate: false,
      redirectEdit: false,
      edit: false,
    };
  }

  componentDidMount() {
    const {
      getCompany,
      location: { pathname },
    } = this.props;
    if (pathname.substring(11) !== 'create') { // checks the URL if it is in edit mode 
      getCompany(pathname.substring(16));
      this.setState({
        edit: true,
      });
      this.setState({
        name: this.props.company.name,
        contactMail: this.props.company.contactMail,
      });
    }
  }

    onChange = (e, { name, value }) => { // method to update the state with modified value in input
      this.setState({ [name]: value });
    };

  handleSubmit = values => {
    const { createCompany, getCompanies } = this.props;
    createCompany(values);
    this.setState({ redirectCreate: true });
    getCompanies(this.props.query);
  };

    handleSubmitEdit = e => {
      e.preventDefault();
      const { name, contactMail } = this.state;
      const { updateCompany } = this.props;
      updateCompany(this.props.company._id, {
        name,
        contactMail,
      });
      this.setState({ redirectEdit: true });
    };

  render() {
    let title = 'Create Company';
    let buttonName = 'Create';
    let submit = this.handleSubmitCreate;

    const { redirectCreate, redirectEdit } = this.state;

    if (redirectCreate) {
      return <Redirect to="/companies" />;
    }

    if (redirectEdit) {
      return <Redirect to={`/companies/${this.props.company._id}`} />;
    }

    if (this.state.edit) {
      title = 'Edit Company';
      buttonName = 'Edit';
      submit = this.handleSubmitEdit;
    }

    const initialValues = {
      name: '',
      contactMail: '',
    };
    const requiredErrorMessage = 'This field is required';
    const emailErrorMessage = 'Please enter a valid email address';
    const validationSchema = Yup.object({
      name: Yup.string().required(requiredErrorMessage),
      contactMail: Yup.string()
        .email(emailErrorMessage)
        .required(requiredErrorMessage),
    });
    return (
      <Layout>
        <div>
          <Button type="submit" form="amazing">
            Create company
          </Button>
          <Button onClick={() => this.props.history.goBack()}>Discard</Button>
          <div>Create company</div>
        </div>

        <Formik
          htmlFor="amazing"
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={values => this.handleSubmit(values)}>
          {({ values, errors, touched, setValues }) => (
            <Form id="amazing">
              <Grid columns={2}>
                <Grid.Column>
                  <Label>Company Name</Label>
                  <Field
                    name="name"
                    as={Input}
                    placeholder="Hello"
                    value={this.state.name || ''} // takes the value from the state
                    onChange={this.onChange} // does the changing 
                  />
                  <div>{touched.name && errors.name ? errors.name : null}</div>
                </Grid.Column>

                <Grid.Column>
                  <Label>Contact Mail</Label>
                  <Field
                    name="contactMail"
                    as={Input}
                    placeholder="[email protected]"
                    value={this.state.contactMail || ''} // takes the value from the state
                    onChange={this.contactMail} // does the changing 
                  />
                  <div>
                    {touched.contactMail && errors.contactMail
                      ? errors.contactMail
                      : null}
                  </div>
                </Grid.Column>
              </Grid>
            </Form>
          )}
        </Formik>
      </Layout>
    );
  }
}

...

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

これを解決し、フィールドを編集可能'This field is required'にして、フィールドにすでにデータがある場合にメッセージを削除する方法についてのアイデアはありますか?

回答

1 LuisPauloPinto Sep 08 2020 at 01:54

3つの小さな変更を行う必要があります。

1.初期値は常に次のように設定されます。

const initialValues = {
   name: '',
   contactMail: '',
};

次のように変更する必要があります。

const initialValues = {
   name: this.state.name,
   contactMail: this.state.contactMail,
};

追加2.enableReinitializeFormik

nº1を変更しても、送信はエラーをスローします。これは、コンポーネントが作成されたときに、Formikコンストラクターからの値でレンダリングされるためです。

this.state = {
      name: "",
      contactMail: "",
      redirectCreate: false,
      redirectEdit: false,
      edit: false,
    };

あなたは状態の内部を変更した場合やcomponentDidMountFormik更新値に再初期化されていません。

componentDidMount() {
    const {
      getCompany,
      location: { pathname },
    } = this.props;
    if (pathname.substring(11) !== 'create') { // checks the URL if it is in edit mode 
      getCompany(pathname.substring(16));
      this.setState({
        edit: true,
      });
      this.setState({
        name: this.props.company.name,
        contactMail: this.props.company.contactMail,
      });
    }
  }

したがって、formikを再初期化するenableReinitializeには、次のように追加する必要があります。

  <Formik
     htmlFor="amazing"
     /// HERE'S THE CODE
     enableReinitialize
     initialValues={initialValues}
     ....

3.を使用するとenableReinitializeFormikぼかしと変更で検証がトリガーされます。これを回避するvalidateOnChangeにはvalidateOnBlur、falseに追加します。

 <Formik
   htmlFor="amazing"
   enableReinitialize
   validateOnChange={false}
   validateOnBlur={false}
   initialValues={initialValues}
   .....