初始化和更改 Formik React-Select 值的问题

时间:2021-07-14 19:13:51

标签: reactjs formik setstate react-select

我正在使用 Formik 构建一个 React 表单,我的一个字段使用了 react-select。使用我的表单添加和提交数据非常简单,并且按预期工作。但我还希望编辑数据,因此我正在努力将数据传递到我的表单并设置我的 react-select 字段值。我在设置 react-select 的默认值并更新这些值(视觉上和表单内部字段数据)时遇到问题。

我尝试通过 initialValue 从我的表单传递值。在提交时,我可以看到在我的表单中提交的原始数据,而无需在选择字段中添加任何内容。但是我没有直观地看到数据,它只是空的。请参阅下面有关编辑在其他字段中填写的数据的屏幕截图,并在提交时发出警报以显示数据。在填写表单提交的数据时,表单类别字段显然是空的:

enter image description here

我已尝试设置我的 <Select> 的 value 属性。这确实显示了我的数据,但之后我似乎无法更改视觉数据(尽管表单内部值正在更改)。所以,我知道我有能力在视觉上预设字段数据。请参阅下面关于编辑传入数据的内容:

enter image description here

由于我之前的尝试,我假设在视觉上和内部显示数据的最佳选择是使用类 state 跟踪它。我已更新 Select 的 onChange 属性以调用 setCategoriesField。不幸的是,当我在类构造函数中明确定义的状态上调用 this.setState 时,我收到一个未定义的错误。见下文

enter image description here

我不知道如何设置我的选择默认初始值,然后从选择字段中添加/删除选项。

注意:我已经删除了我用来限制我在下面共享的代码的额外字段,以便在其他字段正常工作时更易于阅读。

从我的 npm,我有以下版本:

  • 反应:17.0.2
  • 反应选择:4.3.1
import React from 'react'
import { Formik, Form} from 'formik'
import * as Yup from 'yup'

import 'bootstrap/dist/css/bootstrap.min.css'

import Select from 'react-select';
import { TextInput } from './fields/TextInputField'


export default class Form extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      formCategoriesOptions: formCategoriesOptions,
      categoriesOptions: categoriesOptions,
      usptoSelectOptions: usptoSelectOptions
    }
    //this.setCategoriesField = this.setCategoriesField.bind(this)
    //this.setCatelogPageField = this.setCatelogPageField.bind(this)
  }

  setCategoriesField = (e, setFieldValue) => {
    var categoryArray = []
    e.forEach(option => {
      categoryArray.push(option)
    })
    setFieldValue("categories", categoryArray)
    
    this.setState({
      formCategoriesOptions, categoryArray
    })
  }
  render() {
    return (
      <>
        <Formik
          initialValues={{
            categories: this.state.formCategoriesOptions,
            title: this.state.title,
            description: this.state.description,
          }}
          enableReinitialize
          validationSchema={Yup.object({
            title: Yup.string()
              .required('Required'),
            description: Yup.string()
              .required('Required'),
          })}
          onSubmit={(values, { setSubmitting }) => {
            setTimeout(() => {
              alert(JSON.stringify(values, null, 2))

              console.log((JSON.parse(JSON.stringify(values))))

              // SubmitForm(values)

              setSubmitting(false)
            }, 400);
          }}
        >
          {({ errors, touched, isSubmitting, setFieldValue }) => (
            <Form className="form-wrapper">
              <h1>Form</h1>
              <br />
              <div className="form-row">
                <div className="form-group col-6">
                  <label>Categories</label>
                  <Select
                  value={this.state.formCategoriesOptions}
                    name="categories"
                    placeholder="Select all that apply"
                    closeMenuOnSelect={false}
                    isMulti
                    onChange={(opt, e) => {
                      this.setCategoriesField(opt, setFieldValue)
                    }}
                    options={this.state.categoriesOptions}
                    error={errors.categories}
                    touched={touched.categories}
                  />
                  {touched.categories && errors.categories ? (
                    <div className="error invalid-feedback d-block">{errors.categories}</div>
                  ) : null}
                </div>
              </div>
              <div className="form-row">
                <TextInput
                  label="Title"
                  name="title"
                  type="text"
                  placeholder="0000"
                  colSize="col-12"
                />
              </div>
              <div className="form-row">
                <TextInput
                  label="Description"
                  name="description"
                  type="text"
                  placeholder="0000"
                  colSize="col-12"
                />
              </div>

              <button type="submit" className="btn btn-primary" disabled={isSubmitting.isSubmitting}>{isSubmitting.isSubmitting ? "Please wait..." : "Submit"}</button>
            </Form>
          )}
        </Formik>
      </>
    )
  }
}

0 个答案:

没有答案