Formik添加新的值数组,而不是仅添加值

问题描述

我有一个包含卡片的表单,用户需要在其中选择废弃的卡片。此表单使用useFormik钩子和yup进行验证。代码如下:

form.tsx中声明formik

export const validationSchema = object().shape({
  name: string().required(),networks_ids: array().min(1),players_ids: array().min(1),})

export const useForm = () => {
  const formik = useFormik<IFormikValues>({
    initialValues: {
      name: '',networks_ids: [],players_ids: []
    },validationSchema,

然后父组件看起来像这样(不同的文件):

{networks?.map((wspace,index) => (
                <div key={index}>
                  <NetworkSelectCard
                    formik={formik}
                    name={`networks_ids[${index}]`}
                    network={wspace!}
                    value={wspace?._id}
                  />
                </div>
))}

子组件

const NetworkSelectCard: FC<NetworkSelectCardProps> = ({
  formik,name,network,value,}) => {
  return (
    <SelectCardFormik {...{ formik,value }}>
         **Some JSX in here***
    </SelectCardFormik>

一个子组件又位于另一个文件

export const SelectCardFormik: FC<SelectCardFormikProps> = ({
  formik,...props
}) => {
  const Meta = formik?.getFieldMeta(props.name!)
  return (
    <SelectCard
      {...props}
      checked={Meta?.value?.length > 0}
    />
  )
}

最后:

const SelectCard: FC<SelectCardProps> = (props) => {
  const { type,disabled,children,checked,onChange } = props
  const inputRef = useRef<HTMLInputElement>(null)

  return (
***More out of context JSX in here***

        <input
          ref={inputRef}
          name={name}
          type={type || 'checkBox'}
          checked={checked}
          value={value}
          onChange={onChange}
          readOnly
       />

现在的问题是,如果console.log(formik.values)我看到它正在这样做:

{
  "name": "My dope name","networks_ids": [
    [
      "5f33eb0873c9ef232a58cf53"
    ],[
      "5f33eb0873c9ef232a58cf54"
    ]
  ],"players_ids": [],// Should be and array of strings and not an array of arrays

我真的不明白这是如何发生的,也许我错过了一些东西,因为这是我第一次使用Formik。 如果未选择任何卡,则需要禁用“下一步”按钮。因此,我也可以尝试在onSubmit上展平数组,但是为此,我需要调整我的schemaValidation,这也让我很难理解如何验证数组为空还是仅包含数组的情况。空无一物。因为取消选择卡时,它只会删除数组内部的ID,但会保留一个空数组,如下所示:

"networks_ids": [
    [],[
      "5f33eafa73c9ef232a58cf52"
    ]
  ],

对于长久的问题我很抱歉,但是我已经花了很多时间来解决这个问题,我在任何地方都找不到解决方案。 谢谢

解决方法

很难理解您所解释的内容。但是,如果您想让解决方案使用networks_ids,请使用

networks_ids.flat() // returns array of string