Home  >  Q&A  >  body text

Problem with invalid defaultValue or value in FormItem ANTD

<p>I tried using the following code but the fields are not bound. onChange attribute works fine</p> <pre class="brush:php;toolbar:false;">const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form; const NameError = isFieldTouched("Name") && getFieldError("Name"); <FormItem validateStatus={NameError ? "error" : ""} help={NameError || ""}> {getFieldDecorator("Name", { //initialValue: this.state.Data.Name, rules: [{ required: true, message: "Please input the component name!" }] })( <Input className="form-control" type="text" name="Name" defaultValue={this.state.Data.Name} onChange={this.onChange} /> )} </FormItem></pre> <p>Am I missing something? I even used <code>input</code> instead of <code>Input</code></p> <p><strong>Edit</strong> In the <code>componentDidMount</code> method, I get the data from the API: </p> <pre class="brush:php;toolbar:false;">fetch('http://localhost:5728/Fields/get/' this.state.Data.Id) .then(results=>{ return results.json() }) .then(data=>{ this.setState({ Data: { Id: data.field.Id, Name: data.field.Name, Description: data.field.Description, Value: data.field.Value } }) })</pre> <p>I tried using <code>initialValue</code> but that only works if the state value is set in the <code>constructor</code> method. Changes are not reflected when calling the API. </p>
P粉265724930P粉265724930446 days ago450

reply all(2)I'll reply

  • P粉940538947

    P粉9405389472023-08-23 14:57:55

    You can also use hooks

    import { Form } from "antd"
    
    const [form] = Form.useForm();
    
     fetch('api')
          .then(results=>{
            return results.json()
          })
          .then(data=>{
            form.setFieldsValue({
               sample: data.dataYouWant
            });
    
    
    <Form form = {form}>
       <Form.Item name = "sample">
           <Input />
       </Form.Item>
    </Form>

    reply
    0
  • P粉078945182

    P粉0789451822023-08-23 12:33:30

    The documentation states:

    When data is loaded from the backend, just call setFieldsValue:

    fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
          .then(results=>{
            return results.json()
          })
          .then(data=>{
    
            this.props.form.setFieldsValue({
                    Id: data.field.Id,
                    Name: data.field.Name,
                    Description: data.field.Description,
                    Value: data.field.Value
              })
          })

    Or more succinctly, if the backend's data.field exactly matches the field name:

    this.props.form.setFieldsValue(data.field)

    reply
    0
  • Cancelreply