首页 > 解决方案 > 使用 setFieldValue Ant 设计设置字段值

问题描述

我正在使用 react 并使用 Ant Design v4.1.0。
我有一个表单,在提交时(onFinish),我将 id 发送到 reducer 以获取字段的所有值。我这样做是因为我的要求(我必须在表单本身上选择 id 并多次获取所有数据,也可以从许多具有特定 id 的地方打开相同的表单)。可能有更好的方法来实现我的要求,但现在我正在这样做。

我正在获取所需的数据 - 道具(我已验证),但我无法使用新道具更新字段。

我已经设定

class CustomForm extends React.Component {
  formRef = React.createRef();
  constructor()
    render(){
      return(
        <Form 
          ref={this.formRef} 
          onFinish={this.onFinish} 
          name="customForm"
          initialValues=
           {{
             //(trying) email: this.props.customerData.map((d) => d.email)
           }}
        >
          <Form.Item label="Email" name="email">
            <Input />
          </Form.Item>
        </Form>
      )} 
}

我阅读了ant 设计文档,其中提到初始值不适用于状态更改,我们应该使用 setFieldsValue。

尝试时,我根据他们的示例为基于类的表单添加了“formRef”,但无法使用 setFieldValue。
我试过了

componentDidUpdate(){
    alert(JSON.stringify(this.props.customerData.map((d) => d.email)));
    this.formRef.current.setFieldsValue({
      mobileNumber: this.props.customerData
        .map((d) => d.mobile_number),
      email: this.props.customerData.map((d) => d.email),
    });
   }

并得到错误Cannot read property 'setFieldsValue' of null

如何设置值,实际使用 setFieldValues?
为什么 this.formRef 为空?

标签: reactjsantd

解决方案


所以在 onFinish 我设置 loading = true 我的回报是

(this.state.loading ? <Spin /> : <Form />)

我得到 this.formRef = null 的原因。

现在解决了这个问题。

谢谢


推荐阅读