Ant-design: form.setFields(Value) doesn't update the state in the calling component

Created on 9 Mar 2018  ·  8Comments  ·  Source: ant-design/ant-design

Version

3.2.3

Environment

react

Reproduction link

https://codesandbox.io/s/k32ypxw8rv

Steps to reproduce

Enter some text in the "name" field.

What is expected?

The value of the "days" fields to be updated accordingly.

What is actually happening?

Nothing happens, the value of the "days" field is not updated.


To make it works, I need to manually enter a value in the "days" field. But my goal is to programmatically update the field value.

🐛 Bug

Most helpful comment

I hope I did it right. This is my first PR ever :)

All 8 comments

1

You are right, I think it is a bug.

Do I use the form component correctly? Do you know if there is any workaround I could use?

When you modify the value of name, it will trigger onFieldsChange once, and then you use setFieldsValue to trigger onFieldsChange again. So, you this.setState twice, but the second time, you use the old state.

  handleFormChange = changedFields => {
-  this.setState({
-    fields: { ...this.state.fields, ...changedFields }
-  });
+  this.setState(({ fields }) => ({
+    fields: { ...fields, ...changedFields }
+  }));
  };

The sample in the documentation has this code:

 handleFormChange = (changedFields) => {
    this.setState({
      fields: { ...this.state.fields, ...changedFields },
    });
  }

I think the documentation should be updated to avoid further issues.

@pellea just PR to update docs, thanks.

@benjycui The project doesn't lint correctly and I can't commit the code.

git commit -n

I hope I did it right. This is my first PR ever :)

Was this page helpful?
0 / 5 - 0 ratings