Problem with invalid defaultValue or value in FormItem ANTD
P粉265724930
2023-08-22 23:51:25
<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>
You can also use hooks
The documentation states:
When data is loaded from the backend, just call
setFieldsValue
:Or more succinctly, if the backend's
data.field
exactly matches the field name: