简体   繁体   中英

how to use ant design form initialValue

Which is right using antd Form initialValue?

I want to know that if antd form initialValue is using to set initial data or just to show value when the form doesn't have value.

const Component = ({ id }) => {
  const initialName = 'John'
  const { data } = useQuery(GET_NAME, { variables: { id } })
  if (data) { 
    initialName = data.name 
  }

  return (
  <Form.Item>
    {form.getFieldDecorator('name', { initialValue: initialName })(<Input />)}
   </Form.Item>
 )
}

const Component = ({ id }) => {
  const { data } = useQuery(GET_NAME, {
    variables: { id },
    onCompleted: res => { form.setFieldsValue({ name: res.data.name }) }
  })

  return (
  <Form.Item>
    {form.getFieldDecorator('name', { initialValue: 'John' })(<Input />)}
   </Form.Item>
 )
}

You should wrap your form items with the Form component and add the initial value to the Form instead of the Form.Item.

For example:


<Form
      initialValues={{ username:'default value' }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>
    </Form>

yeah the doc is clear I made a mistake instead of initialValue I used initialValues in getFieldDecorator. Also make sure of the version you are using Ant 3.x initiate their values in getFieldDecorator wereas 4.x with initialValues as attribute of Form

For me, setting the initialValues works if it an object that is already present when the form loads, let's sat it is "static". However, when that object is fetched async (using a useEffect hook), initialValues or even settings initialValue on the form's items, doesn't seem to work. Any thoughts?

It will set the value to what you assign initialValue to, so the first approach is right

you can check it here https://ant.design/components/form/#API

Using "setFieldsValue" inside useEffect works amazing!

useEffect(() => {
    props.form.setFieldsValue({
        someFormField: formCalculatedValue,
    });        
}, [someDependencies]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM