gpt4 book ai didi

javascript - 为古腾堡最新帖子 block 启用分页

转载 作者:行者123 更新时间:2023-12-04 13:58:01 25 4
gpt4 key购买 nike

我想将分页添加到古腾堡的最新帖子中。此块通过 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'); } ),
这种方法可行,但我在使用 console.log 时得到了保证 function(props) 中的 numberOfPages Prop .所以我觉得在 withSelect 中添加一个 apiFetch 不是要走的路,是吗?

最佳答案

我还没有找到正确获取页数的解决方案,但我作为一种变通方法是使用与主查询相同的参数运行一次额外的 getEntityRecords 查询,只将顺序反过来(设置orderby 参数为 ascdesc )并将其限制为仅一项( per_page 设置为 1 )。由此我得到了目标集中的最后一项。一旦我有了它,我就可以将 ID 与主分页查询返回的实体的所有 ID 进行比较。一旦我找到主查询返回的集合中最后一项的 ID,我就知道这是最后一页,所以我可以禁用“加载下一页”按钮左右。
这不是一个完整的解决方案,因为它无法提前知道将有多少页面,但仍然比让用户点击“加载更多”直到他们放弃为止都无济于事要好。

关于javascript - 为古腾堡最新帖子 block 启用分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com