使用来自react-admin / react中的API的响应数据初始化表单

时间:2019-04-08 09:54:18

标签: reactjs react-admin

在我的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>
);

1 个答案:

答案 0 :(得分:0)

这样做:

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} />
);