我如何在古登堡/区块编辑区块中获得当前的帖子ID?

时间:2018-11-30 作者:JakeParis

我想从块内访问当前的帖子ID。根据this documentation page, 看来我应该可以通过以下方式获得帖子ID:

wp.data.getCurrentPostId();
// or
wp.data.withSelect(\'core/editor\').getCurrentPostId();
// or
wp.editor.getCurrentPostId();
但这些都不正确。

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

要简单地获取值,可以调用选择器:

const post_id = wp.data.select("core/editor").getCurrentPostId();
在这种情况下,post id不会更改,因此可以将该值赋给组件外部的常量:

const { Component } = wp.element;
const { getCurrentPostId } = wp.data.select("core/editor");
const post_id = getCurrentPostId();

// class component
class ExampleClassComp extends Component {
    render() {
        return <div>{post_id}</div>;
    }
}

// functional component
const ExampleFunctionalComp = () => {
    return <div>{post_id}</div>;
};
但如果值发生更改,则最好将组件连接到存储(例如,如果使用getGlobalBlockCount()). 因此,每次值更新时,选择器都会重新渲染组件。以下是一个示例:

类组件:

const { Component } = wp.element;
const { withSelect } = wp.data;

class ExampleClassComp extends Component {
    render() {
        const { post_id, block_count } = this.props;

        return <div>{block_count}</div>;
    }
}

export default withSelect(select => {
    const { getCurrentPostId, getGlobalBlockCount } = select("core/editor");

    return {
        post_id: getCurrentPostId(),
        block_count: getGlobalBlockCount()
    };
})(ExampleClassComp);
功能组件:

const { useSelect } = wp.data;

export const ExampleFunctionalComp = () => {
    const post_id = useSelect(select =>
        select("core/editor").getCurrentPostId()
    );

    const block_count = useSelect(select =>
        select("core/editor").getGlobalBlockCount()
    );

    return <div>{block_count}</div>;
};

相关推荐