【问题标题】:Initializing a form with response data from an API in react-admin/react在 react-admin/react 中使用来自 API 的响应数据初始化表单
【发布时间】:2019-08-29 10:38:05
【问题描述】:

在我的 react-admin 应用程序中有一个表单 FooCreate。打开此表单时,我想使用从外部 API 检索的数据填充表单元素的默认值。

我读到componentDidMount() 通常是调用外部 API 的首选位置。该 URL 被调用,但我不知道如何将响应数据传递给我的 FooCreate 表单。

我该怎么做

class MyCreate extends Create {
    async componentDidMount() {
        try {
            const response = await API.get("/foo");
            // response contains a field like response.name
            // How can populate the below FooCreate with default values retrieved in response?
        } catch (error) {
            console.error(error);
        }
    }
}

export const FooCreate = props => (
    <MyCreate {...props}>
        <SimpleForm>
            {/* This input element shall be populated with the value from response.name */}
            <DisabledInput source="name" defaultValue="John Doe" />
        </SimpleForm>
    </MyCreate>
);

【问题讨论】:

    标签: reactjs react-admin


    【解决方案1】:

    这样做:

    class MyCreate extends Create {
    
        constructor(props) {
          super(props);
          this.state = {};
        }
    
        async componentDidMount() {
            try {
                const response = await API.get("/foo");
                this.setState({response})
            } catch (error) {
                console.error(error);
            }
        }
    
       render() {
            return <SimpleForm>
                {this.state.response}
                <DisabledInput source="name" defaultValue="John Doe" />
            </SimpleForm>
       }
    }
    
    export const FooCreate = props => (
        <MyCreate {...props} />
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-31
      • 2022-12-10
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 2020-03-22
      • 2021-10-23
      相关资源
      最近更新 更多