繁体   English   中英

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

[英]How to get JSON data from custom end point of WP Rest Api and apply it to Gutenberg custom block component

我想从我制作的自定义端点获取 JSON object 并将其用作 React Select 组件的选项。

注册我的自定义端点

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

web 浏览器显示的 JSON object 如下所示。 我认为这很好。

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

编辑我的古腾堡自定义块的 function。

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>

先感谢您。

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

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

这会将您的组件的 state 设置为将您的 json 从您的端点放入一个名为 options 的属性中。

然后返回硬编码数据的位置,调用 state。

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

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

if(this.state.options) {
    return(...) //your components return
} else {
    return <p>Loading</p>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM