我试图使用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 />
</>
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/>