ant-design: You cannot set field before registering it when set the value to dynamic form item

Version

3.1.1

Environment

MAC 、chrome 63.0.3239.84 (64)、antd 3.1.1

Reproduction link

https://ant.design/components/form-cn/#components-form-demo-dynamic-form-item

Steps to reproduce

Dynamic form item set value,
` const formItems = keys.map((k, index) => { return ( <FormItem {…formItemLayoutWithOutLabel} required={true} key={k} > {getFieldDecorator( minAmount-${k} , { rules: [{ required: true, message: “请输入大于0的值”, }], })( <InputNumber min={0.01} style={{ width: ‘10%’, marginRight: 8 }} disabled={this.state.saveDisable} placeholder=“大于0的值” step={0.01} /> )}

      { (keys.length > 1) ? (
        <Button
        type="danger"
        disabled={keys.length === 1}
        onClick={() => this.remove(k)}
        >删除</Button>
      ) : null}
    </FormItem>
  );
});

Example this.props.form.setFields( { "minAmount-1" : {value : 111} } ); .

What is expected?

Set value as common fields.

What is actually happening?

You cannot set field before registering it.


When edit the row data and set the data to dynamic form item .

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 49 (7 by maintainers)

Most upvoted comments

if your form doesn’t have the fields these you set, this error will appear!

Same problem. English please.

@naefl As warning stated, you can not call setFieldsValue before field been registered.

Hello @kerrzhao, we use GitHub issues to trace bugs or discuss plans of Ant Design. So, please don’t ask usage questions here. You can try to ask questions on Stack Overflow or Segment Fault, then apply tag antd and react to your question.

就像警告说的,你不能在 field 注册前去设置它的值,你在 componentDidMount 里设置 names_2 的值的时候,它还没有被注册。

@naefl try ‘setFields’ instead

setFieldsValue这个方法调用的时候,form没有注册,使用setFields试试看 @kerrzhao

if field not set, warning too. so, first set field, like: form.getFieldDecorator('fieldName', { initialValue: {} }) in render(), then setFieldValue in your methods.

it works for me~

多数是写错label了

@naefl We can use the initialValue instead and set the field value to state example :https://codesandbox.io/s/3rxj27q281

表单组件里只有A和B,而你set的对象里多了一个C

use getFieldDecorator’s initialValue instead setFields or setFieldsValue

Make sure field registered before setFieldsValue

const { form } = this.props;
if (undefined !== form.getFieldValue('foo')) {
  form.setFieldsValue({
    foo: 'hello world',
  });
}

Having this same issue:

Occurs occasionally, but never the first time a component is mounted on React Native.

What is strange about this, is that setFieldValues should only be called well after the form has rendered.

class Login extends React.Component {
  componentDidMount() {
    this.getStoredSettings()
  }
  getStoredSettings = async () => {
    const canLogin = await getItem('token')
    if (!canLogin) {
      const creds = await getItem('credentials')
      if (creds) {
        // update values with creds
        const { email, password } = JSON.parse(creds)
        try {
          this.props.form.setFieldsValue({
            email,
            password,
          })
        } catch (error) {
          console.log(error)
        }
      }
    }
  }

  render() {
    const { form, initialValues } = this.props
    const { email, password } = initialValues
    const { getFieldProps } = form
    return (
            <Form>
              <InputItem
                {...getFieldProps('email', {
               initialValue: email,
             })}
              />

              <InputItem
                {...getFieldProps('password', {
               initialValue: password,
             })}
                type='password'
              />
            </Form>          
    )
  }
}

const LoginForm = createForm()(Login)

const mapState = (state) => {
  return {
    initialValues: {
      email: __DEV__ ? DEFAULT_EMAIL : '',
      password: __DEV__ ? DEFAULT_PASSWORD : '',
    },
 }
}

export default connect(mapState)(LoginForm)

@kerrzhao I’m trying to put setFieldsValue in setState after, the warning is disappear and the problem is solved;

the code is below:

this.setState({ addOptionsList: newAddOptionsList }, () => { setFieldsValue({ [modifyedContent${value}]: '' }); });

i has the same issue,the reason is that,et a value to fields that form does not exist

try form.getFieldDecorator('fieldName', { initialValue: your_value })

The error should really say: “You cannot set field before rendering a field associated with the value.”

“Registering” sounds like the problem is internal to the Ant framework, and has no meaning to new developers.

I having this same issue: You cannot set field before registering it. but the reason was finally found:I set a value to fields that form does not exist,caused an error to appear! Thanks @yanzishang,your answer gave me great help in solving problems.

For me, the issue was due to me calling setFieldsValue with an object that had several fields, while my form only had one field.

Here is a function you can use to

const  dataIWantToFillFormWith = { "test1": "dummy data", "test2": "more dummy data" }

Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = dataIWantToFillFormWith[key] || null;
       setFieldsValue(obj)

Using that function, it will ignore any fields that do not exist in the form.

why not like this ? const formData = { name: data.name, title: data.title, desc: data.desc, link: data.link, }; this.props.form.setFieldsValue(formData); maybe is your fields has one not in the from

getFieldsValue 即可。

i had the same problem as my field name is set to a random value ‘astermihagauvlent’, i fixed it by changing the field name to ‘keys’

you set a fields which you don’t have. : )

if your form doesn’t have the fields these you set, this error will appear!

sixsixsix

if your form doesn’t have the fields these you set, this error will appear!

awesome