Problem with invalid defaultValue or value in FormItem ANTD
P粉265724930
P粉265724930 2023-08-22 23:51:25
0
2
423
<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粉265724930
P粉265724930

reply all(2)
P粉940538947

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>
P粉078945182

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!