无法在按钮单击时显示快捷栏通知-通知未定义

时间:2021-09-26 作者:Badan

我试图使用WITHELECT和withDispatch在以下情况下显示管理员通知;“保存”;单击按钮。我使用的代码如下repo 但它抛出了一个错误:“quot;通知未定义;。以下是我使用的代码:

import { Icon, Button, SnackbarList } from \'@wordpress/components\';
import { dispatch, withSelect, withDispatch } from \'@wordpress/data\';
import { compose } from \'@wordpress/compose\';
// Display and Dispatch the notice
const NewNotices = ({ notices, removeNotice }) => {
    
    //Uncaught TypeError: notices is undefined
    const snackbarNotices = notices.filter((notice) => notice.type === \'snackbar\');

    return (
        <>
            <SnackbarList
                className="cwg-admin-notices"
                notices={snackbarNotices}
                onRemove={removeNotice}
            />
        </>
    );
}

export default compose([
    withSelect((select) => ({
        notices: select(\'core/notices\').getNotices(),
    })),
    withDispatch((dispatch) => ({
        removeNotice: dispatch(\'core/notices\').removeNotice,
    })),
])(NewNotices);
<>
//Create the notice on btn click
<Button
   isPrimary
   onClick={() =>
   {
   settings.save();
   dispatch(\'core/notices\')
   .createNotice(
   \'success\',
   __(\'Settings Saved\', \'slug\'),
   {
   type: \'snackbar\',
   isDismissible: true,
   icon: 
   <Icon icon="smiley" />
   }
   );
   }}
   >
   {__(\'Save\', \'slug\')}
</Button>
<NewNotices />
</>

1 个回复
SO网友:Badan

我想出来了。单击“时,组件未重新加载”;“保存”;按钮我包括了compose 渲染方法中的组件和所有组件现在工作正常:

const Notices = ({ notices, removeNotice }) => {

    const snackbarNotices = notices ? notices.filter((notice) => notice.type === \'snackbar\') : [];
    return (
        <>
            <SnackbarList
                className="cwg-admin-notices"
                notices={snackbarNotices}
                onRemove={removeNotice}
            />
        </>
    );
}

const AppNotices = compose(
    withSelect((select) => ({
        notices: select(\'core/notices\').getNotices(),
    })),
    withDispatch((dispatch) => ({
        removeNotice: dispatch(\'core/notices\').removeNotice,
    })),
)(Notices);
--

<Button
   isPrimary
   onClick={() =>
       {
       settings.save();
       dispatch(\'core/notices\')
       .createNotice(
           \'success\',
           __(\'Settings Saved\', \'slug\'),
           {
           type: \'snackbar\',
           isDismissible: true,
           icon: <Icon icon="smiley" />
           }
       );
   }}
   >
   {__(\'Save\', \'slug\')}
</Button>
<AppNotices/>

相关推荐

如何在WordPress 4.7+中使用REST-API进行元查询?

我试图通过元查询进行过滤,但无论我尝试什么,我都无法使其工作。基本上,我希望通过rest API进行此查询:wp-json/wp/v2/books?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]== 我尝试了几个不同的自定义字段,但它总是返回所有post对象。在我的函数文件中,我添加了:function api_allow_m