antd-From setFieldsValue的You cannot set a form field before rendering a field...

1,198 阅读2分钟

「这是我参与11月更文挑战的第18天,活动详情查看:2021最后一次更文挑战

Hope is a good thing, maybe the best of things. And no good thing ever dies.

今天在react的项目开发中使用了 antdForm 组件,有一个动态嵌套表单的需求,需要再一个From.Item组件 onChange的时候去动态的设置另外一个与之有逻辑关系的From.Item 组件。

所以使用到了FromsetFieldsValue方法,但是一个问题也随之而来了,当时通过换个方法修改关联组件的值的时候,浏览器中出现了如下的警告: You cannot set a form field before rendering a field associated with the value,同时关联组件的值也没有任何改变,没有达到我的预期效果。

我此时在想,明明是官方的api为什么没有效果呢,而且我用的是 antd"antd": "^3.26.20" 的版本,应该不会又这么低级的问题才对啊...

通过谷歌大法,发现了很多人也遇到过类似的问题,具体可以看一下: # You cannot set field before registering it when set the value to dynamic form item

然后慢慢的发现了真相:多数是写错label了

哈哈哈,最后我在想我的应该也是类型的问题。经过排查测试最终确定是 写错label

场景复现

动态表单,渲染Form.Item

<Form.Item style={{ margin: 0 }}>
 {getFieldDecorator(`data[${record.id}][${label}]`, {
   rules:[
       {
       validator: validateNumber,
       }
      ]
         initialValue: record[value]?.toString(),
            })(
                <InputNumber style={{ width: '100%' }} />
              )
            )}
          </Form.Item>
          
此处省略500行代码....

getFieldDecorator(id, options) 参数 这个表单用到了嵌套表单

因为是嵌套表单,所有 getFieldDecorator 的第一个入参id也是动态变化的,

解决

首先我们可以通过 getFieldValue() 方法获取表单元素的值。

如果说我们的 id 有错的话,就会出现题目中警告⚠️

// 重置`data[${item.id}][dataValue]`
    const value = this.props.form.getFieldValue(`data[${item.id}][dataValue]`)
    if(value) {
      this.props.form.setFieldsValue({
        [`data[${item.id}][dataValue]`]: null
      })
    }

结语

如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。

文章如有错误之处,希望在评论区指正🙏🙏

欢迎关注我的微信公众号,一起交流技术,微信搜索 🔍 :「 五十年以后