Phi*_*hil 4 wordpress wordpress-gutenberg
我正在构建一个 WordPress 插件,该插件依赖于注册自定义帖子类型时启用的自定义字段。我想检查帖子类型对象中是否custom-fields存在(并且存在true)该键。supports但是,当我调用 时wp.data.select('core').getPostType('post-type'),它会返回undefined。如果我直接从控制台调用它,我会得到我期望的 post 类型对象,所以我不确定为什么它在我的代码中不起作用。
我尝试从几个地方调用这个。
例如,注册插件面板时:
// Loading `wp.editPosts`, `wp.plugins`, etc. excluded for brevity.
const Component = () => {
const postType = wp.data.select('core/editor').getCurrentPostType();
const postTypeObj = wp.data.select('core').getPostType(postType);
if (postTypeObj.supports.hasOwnProperty('custom-fields')) {
return (
<PluginDocumentSettingPanel
name="my-plugin-name"
title={ __('My Plugin Title', 'pb') }
>
<MyPlugin/>
</PluginDocumentSettingPanel>
);
}
return;
};
registerPlugin('my-plugin-name', {
render: Component,
icon: '',
});
Run Code Online (Sandbox Code Playgroud)
或在插件本身内通过withSelect:
// Loading `wp.compose`, `wp.data`, etc. excluded for brevity.
class MyPlugin extends React.Component {
constructor(props) {
super(props);
this.state = {
// I'll do something with this later on
postTypeObj: props.postTypeObj,
};
}
render() {
return (
<div></div>
);
}
}
export default compose([
withSelect(select => {
const {
getCurrentPostType,
} = select('core/editor');
const {
getPostType,
} = select('core');
return {
postTypeObj: getPostType(getCurrentPostType()),
}
}),
])(MyPlugin);
Run Code Online (Sandbox Code Playgroud)
无论我在哪里调用它,post 类型对象都会返回undefined。
我正在使用古腾堡插件版本6.5.0和WordPress版本5.2.3。
任何帮助表示赞赏。
小智 5
调用getCurrentPostType()将返回例如post。您可能也不需要将其包裹起来getPostType。另外,根据https://github.com/WordPress/gutenberg/issues/13555,您将需要 \xe2\x80\x9csubscribe\xe2\x80\x9d ( wp.data.subscribe) 因为这是一个异步调用,因此将返回 null第一次运行它时。
这是 wp.data.select('core') 中的任何内容以及构建在其之上的内容的特征。
问题是 React 正在进行 ajax 调用来获取数据。并且,当响应返回时,将触发另一个渲染。因此,如果您已经考虑到这一点进行了安排,您的代码将再次运行(当响应到达时),并根据届时已为您存储的服务器响应获得非空结果。
换句话说:最初事物是空白的,这些空白将被填充。
(这值得重复,所以请教育其他人关于这个问题。)