要简单地获取值,可以调用选择器:
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>;
};