首页 > 解决方案 > 在另一个字段中调用 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组件,它不会countriesregion字段更改时刷新字段。

我的问题是我不知道这是否是使用subscription属性时的错误,Form或者我使用的form.onChange功能不正确。

标签: reactjsformsreact-final-form

解决方案


绝对是我的代码错误,Field组件以自己的名称订阅更改


推荐阅读