javascript - 如何为formik字段数组设置初始值?
问题描述
我正在尝试为 formik 初始值道具设置一些值。<FieldArray />
如果我的表单不在formik 中使用,这会更容易。
我有两个组件,我的父组件具有我的表单的所有处理函数,然后是我的子组件,其中使用了 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>
);
}}
FeildArray
在上述 onChange 处理程序中,我使用's push 方法推送上述对象。在 push 方法中,有两个属性location
,license
我分别为它们分配defaultLocation
了defaultLicense
。
在字段 Array 中,我有另外两个来自 react select npm 包的多选下拉菜单。如果数组变量 defaultLocation 和 defaultLicense 的长度大于 0,我将它们设置为选择组件的默认值。
<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 }
/>
问题是即使 react select 组件设置了默认值,formik 也无法识别所选值。仅当触发 onChange 处理程序时,Formik 才会识别预选值。
在第一个代码块中,我使用FieldArray
's push 方法用defaultLocation
和defaultLicense
变量初始化位置和许可证属性。defaultLocation 和 defaultLicense 是我在父组件中保存的状态,它们被传递给子组件(使用 formik 传递给表单)。我知道我必须将预选值设置为 formik 初始值,但我不确定我是否使用了正确的方法。
解决方案
推荐阅读
- react-native - 围绕另一个圆圈制作一个圆圈的动画
- scala - 如何将递归函数转换为尾递归版本?
- javascript - 如何使用 axios 和 javascript 为单个元素传递 url 的 id 值
- javascript - 如何使用 Reactjs 使用 oauth2 Password Grant 对用户登录进行身份验证?
- mongodb - Mongo 位置投影 $
- php - Laravel:是否可以将 Session 作为依赖项注入?
- reactjs - SyntaxError:缺少类属性转换
- react-native - 如何修复 React-Native 中的“路由 'Principal' 的组件必须是 React 组件”错误
- influxdb - 为什么这个简单的流入选择查询返回一个空结果?
- assembly - 对于 Cortex-M3,如何优化块复制和右移 + 饱和到 max=5