我有一个 gutenberg 侧边栏,带有一个切换。它工作得很好,但是当我单击Update或Publish时,值不会保存。我甚至在控制台中检查,当我单击ToggleControl
时,值确实会改变,但是当我发布或更新页面时,切换返回一个空数组。是我的代码中有什么不正确的地方,还是我遗漏了什么?
import { registerPlugin } from "@wordpress/plugins";
import { PluginSidebar, PluginSidebarMoreMenuItem } from "@wordpress/edit-post";
import { __ } from "@wordpress/i18n";
import { Fragment } from '@wordpress/element';
import { withSelect, withDispatch } from '@wordpress/data';
import { compose } from '@wordpress/compose';
import { PanelBody, PanelRow, ToggleControl } from '@wordpress/components';
const ShowSideBarToggle = (props) => {
return (
<ToggleControl
label={__('Show Sidebar?', 'starter')}
checked={props.customPostMetaValue}
onChange={props.setCustomPostMeta}
/>
)
}
const CustomSidebarMeta = compose([
withSelect(select => {
return { customPostMetaValue: select('core/editor').getEditedPostAttribute('meta')['showSidebarAttribute'] }
}),
withDispatch(dispatch => {
return {
setCustomPostMeta: function(value) {
dispatch('core/editor').editPost({ meta: { showSidebarAttribute: value } });
}
}
})
])(ShowSideBarToggle);
const MetaFields = () => {
return (
<Fragment>
<PluginSidebarMoreMenuItem
target='meta-page-settings'
>{__('Theme Settings', 'underscores')}</PluginSidebarMoreMenuItem>
<PluginSidebar
name="meta-page-settings"
title="Gutenberg Settings Sidebar"
>
<PanelBody
title={__('This is a panel section', 'awp')}
initialOpen={true}
>
<PanelRow>
<CustomSidebarMeta />
</PanelRow>
</PanelBody>
</PluginSidebar>
</Fragment>
);
}
registerPlugin( 'page-layout-plugin', {
icon: 'smiley',
render: MetaFields
} );
1条答案
按热度按时间zyfwsgd61#
您的代码确实按预期工作;问题是,除非您手动保存或更新post,否则更新后的post meta实际上不会保存。要确认这一点,请在浏览器控制台中运行:
接下来,切换“显示侧边栏?”并运行相同的命令-
showSidebarAttribute
的值没有改变,即使呈现的切换状态改变了。最后,保存文章,然后再次运行命令,文章 meta现在已经更新。重新加载页面并打开侧边栏,切换状态与文章元匹配。
注意:我注册了测试代码所需的post meta: