Wordpress古腾堡通过自定义帖子类型来获取帖子。

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

我想在一个反应古腾堡块中获取数据来填充选择。下面的代码给我提供了Wordpress的帖子,但我想在一个自定义的帖子类型'df_form'中过滤这些帖子。但我想在一个自定义的帖子类型'df_form'中过滤这些帖子。我该怎么做呢?

/**
 * Loading Posts
 */
getOptions() {
    let posts = new wp.api.collections.Posts();

    return ( posts).fetch().then( ( posts ) => {
        if( posts && 0 !== this.state.selectedPost ) {
            // If we have a selected Post, find that post and add it.
            const post = posts.find( ( item ) => { return item.id == this.state.selectedPost } );
            // This is the same as { post: post, posts: posts }
            this.setState( { post, posts } );
        } else {
            this.setState({ posts });
        }
    });

到目前为止,我试过了,但没有成功。

let posts = wp.data.select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });
wordpress wordpress-gutenberg gutenberg-blocks
1个回答
0
投票

当从数据存储中检索时,因为一些数据正在被异步加载,你需要等待直到应用程序状态完全加载。Esp.你的情况下,你调用的数据是依赖于REST API的。你可能需要考虑高阶组件,特别是withSelect或useSelect。

getOptions = withSelect( (select) => { 
    return select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });
} )

这里是使用异步数据的文档。https:/developer.wordpress.orgblock-editorpackagespackages-data#api。

另外,你有没有试过使用古腾堡的api-fetch包?

apiFetch( { path: '/wp/v2/df_form' } ).then( posts => {
    console.log( posts );
} );

这里是文档。https:/developer.wordpress.orgblock-editorpackagespackages-api-fetch。

© www.soinside.com 2019 - 2024. All rights reserved.