首页 > 解决方案 > 反应钩子不改变表单值

问题描述

React 新手并致力于现有项目。我希望当 Select Elment 更改(正确调用 onInstrumentSelected)时,用其相关值填充表单的其他字段,但不起作用。我可以获得正确的数据(在 console.log 中检查),但无法通过相关的新数据重新填写表格。

const { Option, OptGroup } = Select;
const SettingsViewComponent: React.FC<{ base_instruments: any }> = props => {
  
  let [settings, setSettings] = React.useState<ISettings>();
  const instSearch = props.base_instruments;
  let insId = 0;
  React.useEffect(() => {
    async function fetchsettings(ins) {
      getSettings(ins)
        .then(rsp => {
          setSettings(rsp.data);
        });
    }
    fetchsettings(insId)
  }, [insId]);
  const onInstrumentSelected = async (value, option) => {
    insId = option.value;
    const stt= await getSettings(option.value);
    if (stt!= null) {
      console.log(stt.data); //correct data here 
// not working part:
      settings = stt.data
      setSettings(stt.data);

    } else {
      message.error('error');
    }
  };
  return !settings ? (
    <div />
  ) : (
    <Form
      initialValues={settings}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}>
      <Form.Item label="instrument" name="instrumentId">
        <Select onSelect={(val, op) => onInstrumentSelected(val, op)}>
          {instOptions}
        </Select>
      </Form.Item>
      <Form.Item label="Field 1" name="field1" >
        <Input />
      </Form.Item>
      <Form.Item label="Field 2" name="field2" >
        <Input />
      </Form.Item>
      <Form.Item label="Field3" name="field3">
        <Input />
      </Form.Item>
    </Form>);};
export default SettingsViewComponent;

试过的答案 试过的答案

标签: reactjsreact-hooks

解决方案


我从ant.design找到了解决方案并解决了如下问题,关键更改是setFieldsValue在表单上使用:

// some unchanged

  const [form] = Form.useForm();
  const onInstrumentSelected = async (value, option) => {
    const stt= await getSettings(option.value);
    if (stt!= null) {
      console.log(stt.data); //correct data here 
  settings = stt.data
  form.setFieldsValue({ field1: settings.field1});
  form.setFieldsValue({ field2: settings.field2});
  form.setFieldsValue({ field3: settings.field3});

    } else {
      message.error('error');
    }
  };
  return !settings ? (
    <div />
  ) : (
    <Form form={form}
// unchanged

推荐阅读