I had a problem with the ANTD-Form component, and my intuition was that it was definitely not all the problems I could encounter with setFieldsValue, so I put a one here first, and then I’ll summarize and write two again

Warning: You cannot set a form field before rendering a field associated with the value.

I also looked up the translation for this question, which roughly translates to “you cannot set a form field before rendering a field associated with a value.”

background

It was something like this:

A bug was found in the requirement side. A page roughly consisted of a Tabs component, and each TabPane contained a list that could be dynamically added and deleted. When the list data in the TabPane was deleted, the last data was always deleted.

My immediate reaction was that this must be a rendering exception caused by the failure to set the key value! Then I looked up the code. Boy, that’s not the problem… How serious is the boss’s code, how could he make such a stupid mistake…

Then debug checks the data changes and finds that setFieldsValue does not implement the corresponding value when deleting the data. The code looks something like this.

const data = getFieldsValue("data");
const selector = this.state.selector[index];
data[selector].splice(index, 1);
setFieldsValue({data});
Copy the code

It looks like this. It should be big… I can’t remember exactly. The data is not a simple object, and the deleted data is not a layer of data, but an array of data within an array within an object. It’s a little convoluted, but that’s how the code was written… I didn’t rewrite it, so I had to change it.

To solve

In view of this situation, I undertook a series of Baidu behavior and Gu Ge behavior. Of course, there was a lot of feedback, and ultimately it was the improper use of setFieldsValue.

SetFieldsValue is used to assign values to a set of controls.

Here we go! If the assigned control key does not yet exist, the error will be reported. That is, it cannot be assigned until the binding has been done on getFieldDecorator. When using React, you don’t normally assign to a render component without it… If there’s a special case, it’s one I haven’t encountered yet…

Given the above reasons, it can be inferred that the cause of this error is an assignment to an unbound attribute. In the code, the entire data is assigned together, most likely because the part is not bound yet, but at the moment the data is assigned together.

So I’m going to assign individually, but I haven’t used how to assign to an array, or to a field of an object, which is definitely not fixed, which is concatenated. And then I looked up how to assign it individually, and I found that I could assign it this way, right

setFieldsValue({
    data: {
        `key[${index}]`: dataSource
    }
})
Copy the code

You can import this field as a template string