Javascript 如何设置formik字段数组的初始值?
我正在尝试设置一些值以形成初始值。如果我的表单没有在formik中使用Javascript 如何设置formik字段数组的初始值?,javascript,reactjs,forms,formik,Javascript,Reactjs,Forms,Formik,我正在尝试设置一些值以形成初始值。如果我的表单没有在formik中使用,这会更容易 我有两个组件,一个是我的父组件,它拥有我表单的所有处理函数,另一个是我的子组件,其中使用了formik。我需要在初始化时设置formik表单的初始值。下面是我使用push方法的下拉列表代码 <Formik enableReinitialize={defaultLocation.length > 0} initia
,这会更容易
我有两个组件,一个是我的父组件,它拥有我表单的所有处理函数,另一个是我的子组件,其中使用了formik。我需要在初始化时设置formik表单的初始值。下面是我使用push方法的下拉列表代码
<Formik
enableReinitialize={defaultLocation.length > 0}
initialValues={{
smartCabinetRequestArray: []
}}
render={props => {
return (
<Form onSubmit={props.handleSubmit}>
<div className="form-body">
<FieldArray
name="smartCabinetRequestArray"
render={({ remove, push }) => (
<CustomMultiSelect
name="document_type_id"
id="document_type_id"
options={options}
onChange={(name, value) => {
if (value !== null) {
if (value.length > selectedDocumentTypes.length) {
push({
type: "",
document_type_id: "",
document_type_apply_period_id: "",
categories: [],
location: defaultLocation,
license: defaultLicense
});
}
}
props.setFieldValue(name, value);
}}
value={selectedDocumentTypes}
isDisabled={isDocDropDownDisabled}
/>
)
</div>
</Form>
);
}}
问题是,即使react select组件设置了默认值,formik也无法识别所选值。只有在触发onChange处理程序时,Formik才会识别预选值
在第一个代码块中,我使用了
FieldArray
的push方法,使用defaultLocation
和defaultLicense
变量初始化位置和许可证属性。defaultLocation和defaultLicense是我在父组件中持有的状态,这些状态会传递给子组件(传递到带有formik的表单)。我知道我必须将预选值设置为formik初始值,但我不确定是否使用了正确的方法 有什么解决办法吗?我在这里有同样的问题:(@AlmeidaCavalcante!能够通过在onChange函数上使用async await修复此问题,我使用该函数将值推送到字段数组。defaultLicense和defaultLocation是父组件中的两种状态。这些值未设置为formik初始值,因为在onChange触发时它们尚未初始化。使用async await等到这两个状态初始化后,我的问题就解决了。谢谢!我会试试那个。
<CustomMultiSelect
name={`smartCabinetRequestArray[${index}].location`}
id={`smartCabinetRequestArray[${index}].location`}
options={locationOptions}
onChange={(name, value) => props.setFieldValue( name, value)}
onBlur={props.setFieldTouched}
defaultValue={ defaultLocation.length > 0 && defaultLocation }
/>
<CustomMultiSelect
name={`smartCabinetRequestArray[${index}].license`}
id={`smartCabinetRequestArray[${index}].license`}
options={licenseOptions}
onChange={(name, value) => props.setFieldValue( name, value)}
onBlur={props.setFieldTouched}
defaultValue={ defaultLicense.length > 0 && defaultLicense }
/>