【发布时间】:2021-09-02 08:54:43
【问题描述】:
我想在最新的帖子古腾堡块中添加分页。此块通过withSelect() 和getEntityRecords() 获取帖子,类似于block editor handbook。
REST API 返回两个方便的标头字段以用于分页:
“X-WP-Total”和“X-WP-TotalPages”
https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/
有谁知道是否可以在动态块中访问这些标头字段,该块通过withSelect() 和getEntityRecords() 获取帖子并设置页面总数和当前页面的状态?
这是 block.js 的简化版本:
( function( blocks, element, data ) {
var registerBlockType = blocks.registerBlockType,
withSelect = data.withSelect;
registerBlockType( 'mdwpb/latest-posts', {
title: 'latest posts',
icon: 'megaphone',
category: 'widgets',
attributes: {},
edit: withSelect( function( select ) {
return {
// here's where the magic happens, I think..
posts: select( 'core' ).getEntityRecords( 'postType', 'post', {per_page: 1, page: 1})
numberOfPages: ?,
};
} )( function( props ) {
if ( ! props.posts ) {
return "Loading...";
}
if ( props.posts.length === 0 ) {
return "No posts";
}
var className = props.className;
var post = props.posts[ 0 ];
return (
<div>
{ props.posts.map( ( post ) => (
<h3 className={props.className}>
{post.title.rendered}
</h3>
))}
</div>
);
} ),
} );
}(
window.wp.blocks,
window.wp.element,
window.wp.data,
) );
我尝试通过 apiFetch 将 numberOfPages 添加到 withSelect 函数中:
numberOfPages: wp.apiFetch({
path: wp.url.addQueryArgs( 'wp/v2/posts', {per_page: 1, page: 1} ),
parse: false,
}).then( response => { return response.headers.get('X-WP-TotalPages'); } ),
这种方法有效,但是当我在function(props) 中使用 numberOfPages 属性的console.log 时,我得到了一个承诺。所以我觉得向 withSelect 添加一个 apiFetch 不是要走的路,或者是吗?
【问题讨论】:
标签: javascript wordpress pagination react-redux wordpress-gutenberg