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

问题描述 投票:0回答:1

在我的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个回答
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} />
);
© www.soinside.com 2019 - 2024. All rights reserved.