【问题标题】:Unable to maintain formik state values within react-select component无法在 react-select 组件中维护 formik 状态值
【发布时间】:2021-05-10 09:16:17
【问题描述】:

我将 react-select(多值)与 Formik 以及 Material-UI Stepper(向导)一起使用,并将值成功存储在 Formik 的 initialStates 值中,但是当我前进到下一个屏幕时,使用我的条件组件渲染Stepper 然后返回我的 react-select 组件所在的一个屏幕,它不再保存/显示已在我的 react-select 组件中选择的值,即使这些值仍在 Formik 的 initialStates 值中。

我的状态如下,正确存储了我的selectedOptions

import Select from 'react-select';

const myOptions= [
  { value: 'Food', label: 'Food' },
  { value: 'Being Fabulous', label: 'Being Fabulous' },
  { value: 'Unicorns', label: 'Unicorns' },
  { value: 'Kittens', label: 'Kittens' },
];


"props": {
    "myGroups": [
        {
            "myGroupName": "",
            "selectedOptions": [
                {
                    "value": "Unicorns",
                    "label": "Unicorns"
                },
                {
                    "value": "Kittens",
                    "label": "Kittens"
                }
            ]
        }
     ]
 }

这里是 react-select 组件的代码:

<Formik initialValues={initialFormValues} validationSchema={formSchema} onSubmit={this.handleFormSubmit} enableReinitialize>
    {({ handleSubmit, handleChange }) => (
        <Form noValidate onSubmit={handleSubmit} autoComplete='off'>
            <Select
                options={myOptions}
                isMulti={true}
                name={`myGroups.${index}.selectedOptions`}
                onChange={(selectedOption) => {
                    let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOption } };
                    handleChange(e);
                }}
            />
        </Form>
    )}
</Formik>

返回时,我希望在选择中同时看到“独角兽”和“小猫”,但它是空的。

有什么想法可以在这个组件中维护状态吗?我可以以某种方式使用 `defaultValue' 吗?

【问题讨论】:

    标签: reactjs material-ui state formik react-select


    【解决方案1】:

    我找到的唯一解决方案是安装这个库:formik-material-ui

    轻松导入后即可:

    import { Select } from 'formik-material-ui';

    并在Field组件props中使用。

    【讨论】:

    • 嗨,但这对我的问题有什么帮助?您能否提供有关 react-select 的更多信息。
    • 在问这个问题之前,请点击链接尝试一下。
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2019-09-23
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多