我想从一个块中访问当前的帖子 ID。 根据此文档页面,似乎我应该能够通过以下方式获取帖子 ID:
wp.data.getCurrentPostId();
// or
wp.data.withSelect('core/editor').getCurrentPostId();
// or
wp.editor.getCurrentPostId();
但这些都不正确。
要简单地获取值,您可以调用选择器:
const post_id = wp.data.select("core/editor").getCurrentPostId();
在这种情况下,帖子 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>;
};