如何从WP Rest Api的自定义端点获取JSON数据并将其应用于古腾堡自定义块组件

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

我想从我制作的自定义端点获取JSON对象,并将其作为选项反应选择组件。

我的自定义终点的注册

register_rest_route('namespace/v1', 'products', array(
    'methods'  => WP_REST_Server::READABLE,
    'callback' => 'namespace_result_products',
));

Web浏览器显示的JSON对象如下。我认为很好。

[
  {
    "value": 15,
    "label": "Apple"
  },
  {
    "value": 21,
    "label": "Banana"
  },
  {
    "value": 18,
    "label": "Apple"
  },...

我的gutenberg自定义块的编辑功能。

edit: props => {
const { attributes: { selectedOption }, setAttributes } = props;
const handleSelectChange = ( selectedOption ) => setAttributes( { selectedOption: JSON.stringify( selectedOption ) } );
return (
    <InspectorControls>
        <PanelBody
            title={ 'Products'}
        >
            <PanelRow>
                <Select
                    name='select'
                    value={ JSON.parse( selectedOption ) }
                    onChange={ handleSelectChange }
                    options={[
                        // !!!!!!!!  I want to apply my JSON data here  !!!!!!!! 
                    ]}
                    isMulti='true'
                    />
            </PanelRow>
        </PanelBody>
    </InspectorControls>
    )
},

通过硬编码,可以正常工作。

<PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={[
            { value: '15', label: 'Apple' },
            { value: '21', label: 'Banana' },
            { value: '18', label: 'Apple' },
        ]}
        isMulti='true'
        />
</PanelRow>

谢谢你。

javascript json reactjs wordpress wordpress-gutenberg
1个回答
0
投票

在您的组件中,在componentDidMount生命周期方法中进行Ajax调用并设置状态。像这样。

fetch('http://url.com/namespace/v1/products')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      this.setState({
          options: data
    });

这将设置组件的状态,以使来自端点的json位于名为options的属性中。

然后返回您对数据进行硬编码的位置,称为状态。

<PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={this.state.options}
        isMulti='true'
    />
</PanelRow>

如果在设置状态之前尝试安装组件,这将引发错误,因此请确保将return语句包装在检查中。

if(this.state.options) {
    return(...) //your components return
} else {
    return <p>Loading</p>
}
© www.soinside.com 2019 - 2024. All rights reserved.