【问题标题】:Cannot set a default value for MUI Autocomplete with Formik when options are being fetched with useEffect当使用 useEffect 获取选项时,无法使用 Formik 为 MUI 自动完成设置默认值
【发布时间】:2023-01-05 03:27:41
【问题描述】:

我正在尝试将自动完成与 Formik 结合使用,同时使用 useEffect 挂钩获取选项并通过 useState 保存选项数组。它已经集成并且似乎可以正常工作,除非我尝试设置默认值。当我直接设置默认值时,页面显示设置值但它消失了,并在我刷新页面时再次显示该字段为空。

如果我在 intialValues 中使用 formik state 设置它,那么 TextField 中的字符串显示 undefined 并且控制台显示此消息:

Material-UI: The value provided to Autocomplete is invalid.
None of the options match with `211`.
You can use the `isOptionEqualToValue` prop to customize the equality test.

我正在使用 useEffect 来获取选项数组,但为了简单起见,直接在 codesandbox 中添加一个数组。

这是链接: https://codesandbox.io/s/serene-colden-9x75v4?file=/src/App.js

【问题讨论】:

  • 您提到的沙箱没有运行。检查这个example。我用过mui 5
  • 这是可行的,但是一旦我删除 multiplelimitTags={1} 道具,字符串就会显示未定义。
  • 我已经为单个值修改了example。首先,您必须过滤掉该值,然后进行设置。前面的示例是针对多选的,而多选使用数组而不是单个对象值
  • 首先,非常感谢你。我真的很感谢你帮助我。由于您修改过的示例,我能够在理论上解决这个问题并找出问题所在。查看我修改后的example。当我将项目数组设置为静态并预加载到内存中时,它会起作用。但是,一旦我从外部注释掉项目数组并添加 useState(第 17 行)和 useEffect(第 23-30 行),该字段就会再次变空。我需要使用 useEffect,因为我正在获取项目数组以从 API 填充下拉列表。
  • 欢迎,只需在useFormik codesandbox.io/s/goofy-boyd-ogh3lv?file=/src/App.js:1047-1077中添加enableReinitialize: true

标签: reactjs material-ui formik formik-material-ui


【解决方案1】:

我只是为此创建了一个组件

在表格中,您必须通过 FormikProvider 才能与 FormikContext 一起使用


import { TextField } from '@mui/material';
import Autocomplete from '@mui/material/Autocomplete';
import { useFormikContext } from 'formik';
import React from 'react';


type OptionsValues = {
  title: string,
  value: string
}

type Props = {
  id: string,
  name: string,
  label: string,
  options: OptionsValues[]
}

function MuiltSelect(props: Props) {
  const { options, name, label, id } = props

  const formik = useFormikContext();

  return (
    <Autocomplete
      {...props}
      multiple
      options={options}
      getOptionLabel={(option: any) => option.title}
      onChange={(_, value) => formik.setFieldValue(name, value)}
      filterSelectedOptions
      isOptionEqualToValue={(item: any, current: any) => item.value === current.value}
      renderInput={(params) => (
        <TextField
          {...params}
          id={id}
          name={name}
          label={label}
          variant={"outlined"}
          onChange={formik.handleChange}
          error={formik.touched[name] && Boolean(formik.errors[name])}
          helperText={formik.errors[name]}
          value={formik.values[name]}
          fullWidth
        />
      )
      }
    />
  )
}


export default MuiltSelect

检查要点

https://gist.github.com/Wellers0n/d5dffb1263ae0fed5046e45c47a7c4a7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2019-07-28
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多