未捕获的TypeError:wp.apiFetch不是函数

时间:2018-11-28 作者:Chad Holden

我正在使用最新的Gutenberg和WP,直到上周,下面的代码仍按预期工作。

const postSelections = [];

const allPosts = wp.apiFetch({path: "/wp/v2/featured-post"}).then(fps => {
    postSelections.push({label: "Select a Post", value: 0});
    $.each( fps, function( key, val ) {
        postSelections.push({label: val.title.rendered, value: val.id});
    });
    return postSelections;
});
我突然得了wp。apiFetch不是一个函数错误。

有人知道为什么吗??

1 个回复
最合适的回答,由SO网友:Chad Holden 整理而成

正如@Alvero在评论中指出的,现在需要指定wp-api-fetch,而不仅仅是在块注册中提供wp-api。

$index_js = \'sample-post/index.js\';
wp_register_script(
    \'sample-post-block-block-editor\',
    plugins_url( $index_js, __FILE__ ),
    array(
        \'wp-blocks\',
        \'wp-i18n\',
        \'wp-element\',
        \'wp-api-fetch\',
    ),
    filemtime( "$dir/$index_js" )
);
然后在您的块中,使用wp调用它。apiFetch函数:

var registerBlockType = wp.blocks.registerBlockType,
    el = wp.element.createElement,
    __ = wp.i18n.__,
    apiFetch = wp.apiFetch;

const postSelections = [];

const allPosts = apiFetch({path: "/wp/v2/featured-post"}).then(fps => {
    postSelections.push({label: "Select a Post", value: 0});
    $.each( fps, function( key, val ) {
        postSelections.push({label: val.title.rendered, value: val.id});
    });
    return postSelections;
});

结束

相关推荐