withFormik嵌套对象

时间:2019-08-27 21:15:08

标签: javascript reactjs formik

试图将表单的某些元素转换为嵌套对象。我正在使用Formik库和withFormik()函数

我现在下面的内容有效。尽管concreteasphalt在要返回的对象中是它们自己的key:value对。

import React from 'react'
import { withFormik, Form, Field } from 'formik'

const EmployeeForm = ({}) => (
    <Form>
        <label>
            <Field type='checkbox' name='concrete' />
            Concrete
        </label>
        <label>
            <Field type='checkbox' name='densities' />
            Densities
        </label>
        <button type='submit'>Submit</button>
    </Form>
)

const FormikEmployee = withFormik({
    mapPropsToValues({ concrete, densities }) {
        return {
            concrete:concrete || false,
            densities:densities || false
        }
    },
    handleSubmit(values) {
        console.log(values)
    }
})(EmployeeForm)

export default FormikEmployee

我希望Formik返回一个对象,例如

{
    certs:{
        concrete:true,
        densities:false
    }
}

下面的代码是我尝试过的,但是会引发错误。

const EmployeeForm = ({}) => (
    <Form>
        <label>
            <Field type='checkbox' name='certs.concrete' />
            Concrete
        </label>
        <label>
            <Field type='checkbox' name='certs.densities' />
            Densities
        </label>
        <button type='submit'>Submit</button>
    </Form>
)

const FormikEmployee = withFormik({
    mapPropsToValues({ certs: { concrete, densities } }) {
        return {
            certs: {
                concrete:concrete || false,
                densities:densities || false,
            }
        }
    },
    handleSubmit(values) {
        console.log(values)
    }
})(EmployeeForm)

预期的结果将是在mapPropsToValues()中实现Formik,我有一个嵌套对象,并且看到它与我要返回的嵌套对象匹配。 目前,它引发了错误Uncaught TypeError: Cannot read property 'concrete' of undefined

0 个答案:

没有答案