You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gutenberg区块文章分组显示异常求助:交替2/3篇重复且首组不符

修复Gutenberg区块文章分组重复及首组显示问题

问题根源

原代码的核心问题在于遍历文章时动态修改分组大小,导致分组起始位置的判断逻辑混乱,进而出现文章重复渲染;同时首组显示异常是因为第一次生成组后立刻切换了分组大小,后续计算完全偏离预期。

修正后的代码

const { posts, hasPostsResolved } = useSelect(select => {
    const query = {
        order: 'asc',
        orderby: 'title',
        status: 'publish',
        per_page: 10,
    };
    return {
        posts: select('core').getEntityRecords('postType', 'post', query),
        hasPostsResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'post', query]),
    }
}, []);

const displayPosts = (posts) => {
    const groups = [];
    let currentIndex = 0;

    // 首组固定取3篇(文章数量足够时)
    if (posts.length >= 3) {
        groups.push(posts.slice(currentIndex, currentIndex + 3));
        currentIndex += 3;
    }

    // 首组之后交替按2、3篇分组
    let nextGroupSize = 2;
    while (currentIndex < posts.length) {
        const endIndex = Math.min(currentIndex + nextGroupSize, posts.length);
        groups.push(posts.slice(currentIndex, endIndex));
        currentIndex = endIndex;
        // 切换下一组的大小
        nextGroupSize = nextGroupSize === 2 ? 3 : 2;
    }

    return (
        <>
            {groups.map((group, groupIndex) => (
                <div key={groupIndex} className={`post-group posts-${group.length}`}>
                    {group.map((post, postIndex) => (
                        <article
                            id={`post-${post.id}`}
                            className="wp-block-posts-carousel__post"
                            key={`group-${groupIndex}-post-${postIndex}`}
                        >
                            <div className="wp-block-posts-carousel__post-thumbnail">
                                <img 
                                    src="https://placehold.co/1000x700" 
                                    width="1000" 
                                    height="700" 
                                    alt={decodeEntities(post.title.rendered || __('(no title)'))} 
                                />
                                <h2 className="wp-block-posts-carousel__post-title">
                                    {post.title.rendered
                                        ? decodeEntities(post.title.rendered)
                                        : __('(no title)')}
                                </h2>
                            </div>
                        </article>
                    ))}
                </div>
            ))}
        </>
    );
};

return (
    <>
        <div {...blockProps}>
            {!hasPostsResolved && <Spinner />}
            {hasPostsResolved && posts?.length === 0 && (
                <p>{__('No posts found')}</p>
            )}
            {hasPostsResolved && posts?.length > 0 && (
                <div className="wp-block-posts-carousel__posts">
                    {displayPosts(posts)}
                </div>
            )}
        </div>
    </>
);

关键修正点

  • 预处理分组数组:先按规则把文章分成明确的组,避免遍历过程中动态修改分组大小导致的逻辑混乱
  • 首组强制3篇:单独处理首组,确保满足需求的优先级
  • 安全边界处理:使用Math.min避免最后一组超出文章数组长度
  • 优化key值:采用group-index-post-index的命名方式,避免key冲突导致的渲染异常
  • 完善图片alt属性:添加符合语义的alt文本,提升可访问性

内容的提问来源于stack exchange,提问作者leemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:55:36