reactjs - 在另一个字段中调用 form.change(fieldName, value) 不会改变 fieldName 字段
问题描述
我正在尝试使用该Form
组件,subscription={{ submitting: true, pristine: true }}
因此它不会在每次更改时重新呈现整个表单。我有一个字段可以更改表单中另一个字段的值。我希望Field
组件能够订阅对其名称值的更改。在这种情况下,它不会改变,我需要用FormSpy
. 这不是最好的解决方案,因为FormSpy
不能订阅单个值,并且在values
.
这是代码工作,但它不应该需要FormSpy
:
export const CountryForm = ({ regions, countries }) => (
<Form
onSubmit={submittedData => {
console.log({ submittedData })
}}
subscription={{ submitting: true, pristine: true }}
render={({ handleSubmit, form }) => (
<form onSubmit={handleSubmit}>
<FormLabel>Regions</FormLabel>
<FormField
name="region"
render={({ input, ...props }) => (
<Select
options={regions}
input={{
...input,
onChange: (selectedRegion: string) => {
input.onChange(selectedRegion)
const formState = form.getState()
const selectedCountries: string[] = formState.values.countries || []
const countriesFiltered = filter(countries, {
region: selectedRegion,
})
forEach(countriesFiltered, country => {
if (selectedCountries.indexOf(country.code) === -1)
selectedCountries.push(country.code)
})
form.change('countries', selectedCountries)
},
}}
{...props}
/>
)}
/>
<FormLabel>Countries</FormLabel>
<FormSpy subscription={{ values: true }}>
{() => (
<Field
name="countries"
render={props => <Select options={countries} {...props} />}
/>
)}
</FormSpy>
</form>
)}
/>
)
如果没有该FormSpy
组件,它不会countries
在region
字段更改时刷新字段。
我的问题是我不知道这是否是使用subscription
属性时的错误,Form
或者我使用的form.onChange
功能不正确。
解决方案
绝对是我的代码错误,Field
组件以自己的名称订阅更改
推荐阅读
- amazon-web-services - 如何修复 aws elastick beanstalk 的 postgresql 版本错误?
- css - 在以下情况下,Router Link Active 不起作用,它们是否有任何替代方式来动态激活按钮?
- c++ - 错误 C1903 - 调用 offsetof 时无法从先前的错误中恢复
- php - 为什么 flashdata 在 Codeigniter 中不起作用
- python - 使用 pandas 数据框样式器更正行着色
- python - 为 Django CreateView 应用搜索/过滤下拉列表
- c - 这是释放作为结构一部分的多个动态分配的数组的正确方法吗?
- firebase - 使用 Firebase 使用推送 ID 时如何检查现有数据?
- vue.js - 访问动态子组件
- matlab - 在 MATLAB 中绘制时间序列数据