Saber2pr's Blog

异步初始化表单项

表单主动初始化,适合场景:initValues中没有值,但需要提交到表单。初始值需要异步另外请求加载

import { Input, Spin } from 'antd';
import React from 'react';

import { useAsync } from 'hooks/useAsync';

export interface ViewProps {
  id: number;
  value?: string;
  onChange?: (value: string) => void;
}

export const View: React.FC<ViewProps> = ({ value, onChange, id }) => {
  const { loading } = useAsync(async () => {
    // 例如关联表id的查询
    const initValue = await Promise.resolve(`${id}`);
    // 初始化初始值
    onChange(initValue);
  }, [id]);

  return (
    <Spin spinning={loading}>
      <Input value={value} onChange={(event) => onChange(event.target.value)} />
    </Spin>
  );
};