Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

antd pro v4 使用form.setFieldsValue更新数据的时候,form为null,改如何解决?

class List extends React.Component {

  // 详情表单实例
  FormRef = React.createRef();
  
  render() {
        <Form {...layout}
          ref={this.FormRef}
          name="form"
          onFinish={this.create}>
          <Form.Item label="名称">
           <Input allowClear maxLength="64" placeholder="Name"/>
          </Form.Item>
        </Form>
  }
} 

代码大概是上面贴出来的那样子
流程是异步调用接口获取返回数据后使用this.FormRef.current.setFieldsValue({})的时候报错
this.FormRef.current为null。

后面发现如果在表单里按钮触发点击事件,则this.FormRef.current不为null。但是如果在表单了添加按钮主动触发就不是我想要的效果了,既然页面已经渲染了,那么为什么this.FormRef会为null呢?

希望好心人帮助我解决?谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

那个用ref的话需要先渲染一次from表单,才可以使用ref来控制数据,所以需要写一个延迟让组件先渲染

setTimeout(() => {
      this.formRef.current.setFieldsValue({
           //       
      });
      }, 100);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...